Ruby中的str.each无法正常工作

23

我正在学习 Ruby。

我在 http://ruby-doc.org/core/classes/String.html 上找到了方法 String#each

当我尝试使用它时......

irb(main):001:0> "hello\nworld".each {|s| p s}
NoMethodError: undefined method `each' for "hello\nworld":String

...但是我收到了 NoMethodError 的错误。

我正在使用 Ruby 1.9.1p253,因此我不认为我在使用旧版本。发生了什么事?

4个回答

37

10

使用each_char代替:

"hello\nworld".each_char {|s| p s}

关于为什么它不能工作,它在1.8中可以工作但在1.9中不行。


3
String#each 按行迭代,而不是按字符。 - sepp2k

3

您正在查看1.8版本的文档。在1.9版本中,String#each已被删除,请改用each_line。


2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接