Pretty simple question from a first-time Ruby programmer.
How do you loop through a slab of text in Ruby? Everytime a newline is met, I want to re-start the inner-loop.
def parse(input)
...
end
From stackoverflow
-
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_linekeeps the line feed chars, whilespliteats them.Note the regex I used here will take care of all three line ending formats.
String#each_lineseparates lines by the optional argumentsep_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 -
str.each_line.chomp do |line| # do something with a clean line without line feed characters endI think this should take care of the newlines.
Chuck : That won't work. String#each_line without a block returns an Enumerator, which doesn't respond to chomp. Beyond chomp doesn't take a block.
0 comments:
Post a Comment