我正在遍历具有多个回车符的大字符串。我希望我的逻辑每次发现回车符时都要执行一些操作(在回车符之前创建一个具有所有字符串内容的新ActiveRecord实例)。
def doit(str)
start_idx = 0
while i = str.index("\n", start_idx)
action str[0..i-1]
start_idx = i+1
end
end
def action(str)
puts "This is what I've read: #{str}"
end
doit("Three blind mice,\nsee how they run.\nThey all ran after the farmer's wife\n")
# This is what I've read: Three blind mice,
# This is what I've read: Three blind mice,
# see how they run.
# This is what I've read: Three blind mice,
# see how they run.
# They all ran after the farmer's wife
请参见String#index。
如果只希望传递自上一个换行符以来的字符串部分,请更改该行:
action str[0..i-1]
至:
action str[start_idx..i-1]