Search code examples
ruby-on-railsrubystringcarriage-return

How does Ruby detect a carriage return in a string?


I'm iterating through a large string that has several carriage returns. I'd like my logic to do something every time a carriage return is discovered (create a new ActiveRecord instance with all the string content before the carriage return).


Solution

  • 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
    

    See String#index.

    If you only want to pass the portion of the string since the previous newline, change the line:

    action str[0..i-1]
    

    to:

    action str[start_idx..i-1]