String#each_line
str.each_line do |line|
#do something with line
end
What Iraimbilanja said.
Or you could split the string at new lines:
str.split(/\r?\n|\r/).each { |line| … }
Beware that each_line
keeps the line feed chars, while split
eats them.
Note the regex I used here will take care of all three line ending formats. String#each_line
separates lines by the optional argument sep_string
, which defaults to $/
, which itself defaults to "\n"
simply.
Lastly, if you want to do more complex string parsing, check out the built-in StringScanner class.
You can also do with with any pattern:
str.scan(/\w+/) do |w|
#do something
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With