Ruby递归函数问题:实现每隔指定字符数添加换行
Fixing Your Recursive Ruby Function to Add Newlines Every X Characters
Let's break down what's going wrong with your current implementations, then fix the recursive approach to meet your needs.
What's Wrong with Your Current Code
Let's start with your second version (the closer one to working):
def add_newline(len, thing) if thing.length <= len return thing else val = thing[0..len] # Problem 1: This takes len+1 characters (0..len).each { |x| thing[x] = "" } # Problem 2: Strings are immutable in Ruby—this does nothing return val + "\n" + add_newline(len, thing) end end
- Incorrect substring length:
thing[0..len]uses a closed interval, so forlen=2, it grabs characters at indices 0,1,2 (3 total characters) instead of the first 2. You need a half-open interval0...lento get exactlylencharacters. - Immutable strings: Ruby strings can't be modified in-place like that with
thing[x] = ""(well, technically you can with mutable strings, but it's not the right approach here). Instead of trying to modify the original string, just pass the remaining substring directly to the recursive call.
Your first version has even more issues—you're hardcoding 4 in the scan call, only taking the first character with val = thing[0], and passing the original string to the recursive call, which is why you got the weird output.
The Fixed Recursive Implementation
Here's the corrected recursive function that does exactly what you want:
def add_newline(len, thing) # Base case: if the string is short enough, return it as-is return thing if thing.length <= len # Take the first `len` characters, add a newline, then recurse on the remaining substring first_part = thing[0...len] remaining_part = thing[len..-1] "#{first_part}\n#{add_newline(len, remaining_part)}" end
Testing It Out
Let's test your example:
puts add_newline(2, "1234")
This will output:
12 34
Another test case with spaces:
puts add_newline(3, "hello world")
Output:
hel lo wor ld
How It Works
- Base case: When the input string's length is less than or equal to
len, we just return it—no need to split further. - Recursive step: We split the string into two parts: the first
lencharacters (using0...lento get exactlylencharacters), then the rest of the string starting at indexlen(usinglen..-1which means from indexlento the end). We combine the first part with a newline, then append the result of recursively processing the remaining part.
内容的提问来源于stack exchange,提问作者Jraokmepala
相关产品推荐
相关产品推荐

