开发者

Readline, the Input Record Separator and Ruby

开发者 https://www.devze.com 2022-12-23 11:42 出处:网络
In Ruby I\'m looking to read data until I reach a delimiter or the end of the file. I found this is possible by redefining $/ or the $INPUT_RECORD_SEPARATOR to my delimiter. However, with all the \"f

In Ruby I'm looking to read data until I reach a delimiter or the end of the 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 hackey to change the value of a global to do this. Also, readline used to consume the delimiter, while not including it in what is returned.

Is there any other way to "read until" while consuming the delimiter that doesn't involve g开发者_C百科etting the values char by char in a loop?


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"


You can specify the record separator as an argument to gets, e.g.:

while line = gets("\r")
  puts line
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号