tags:

views:

164

answers:

1

In Ruby I'm looking to read data until I reach a delimiter or end of file. I found this is possible by redefining $/ or the $INPUT_RECORD_SEPARATOR to my delimiter. However with all the "features" in the Ruby language it seems hokey to change the value of a global to do this. Also, readline used to consume the delimiter while not it is included in what is returned.

Is there any other way to "read until" while consuming the delimiter that doesn't involve getting the values char by char in a loop?

A: 

Basically, all readline-style methods from IO accept separator string as an optional parameter:

>> s = StringIO.new('hello from string')
=> #<StringIO:0x52bf34>
>> s.readline ' '
=> "hello "
>> s.readline ' '
=> "from "
>> s.readline ' '
=> "string"
Mladen Jablanović
Excellent, how could I use that in a "f.each do |line|" or "while line s.gets"?
JustSmith
`f.each(' '){|s| puts s}`
Mladen Jablanović
For the win! <!-- comment padding -->
JustSmith