Readline、输入记录分隔符和 Ruby [英] Readline, the Input Record Separator and Ruby
问题描述
在 Ruby 中,我希望读取数据,直到到达分隔符或文件末尾.
In Ruby I'm looking to read data until I reach a delimiter or the end of the file.
我发现这可以通过将 $/
或 $INPUT_RECORD_SEPARATOR
重新定义为我的分隔符来实现.然而,有了 Ruby 语言中的所有特性",改变全局的值来做到这一点似乎很困难.此外, readline 用于使用分隔符,但不将其包含在返回的内容中.
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 getting the values char by char in a loop?
推荐答案
基本上,来自 IO
的所有 readline
样式的方法都接受分隔符字符串作为可选参数:>
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"
这篇关于Readline、输入记录分隔符和 Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!