7

I find Ruby's each function a bit confusing. If I have a line of text, an each loop will give me every space-delimited word rather than each individual character.

So what's the best way of retrieving sections of the string which are delimited by a tab character. At the moment I have:

line.split.each do |word|
...
end

but that is not quite correct.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
alamodey
  • 14,320
  • 24
  • 86
  • 112

1 Answers1

19

I'm not sure I quite understand your question, but if you want to split the lines on tab characters, you can specify that as an argument to split:

line.split("\t").each ...

or you can specify it as a regular expression:

line.split(/\t/).each ...

Each basically just iterates through all the items in an array, and split produces an array from a string.

Ben
  • 66,838
  • 37
  • 84
  • 108
  • 1
    It's ok for simple cased. But is not *that* simple. There are number of edge cases when the content comes from external source. The newlines, escape sequences, quotes etc are so different between different apps. – Dmytrii Nagirniak Jan 30 '12 at 00:04