Ruby 如何检测字符串中的回车 return?

How does Ruby detect a carriage return in a string?

我正在遍历一个包含多个回车 return 的大字符串。我希望我的逻辑在每次发现马车 return 时做一些事情(创建一个新的 ActiveRecord 实例,其中包含马车 return 之前的所有字符串内容)。

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]