You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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
  1. Incorrect substring length: thing[0..len] uses a closed interval, so for len=2, it grabs characters at indices 0,1,2 (3 total characters) instead of the first 2. You need a half-open interval 0...len to get exactly len characters.
  2. 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 len characters (using 0...len to get exactly len characters), then the rest of the string starting at index len (using len..-1 which means from index len to the end). We combine the first part with a newline, then append the result of recursively processing the remaining part.

内容的提问来源于stack exchange,提问作者Jraokmepala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:46:29