Ruby中的str.each不起作用

Tom*_*Tom 21 ruby string ruby-1.9

我正在学习Ruby.

String#eachhttp://ruby-doc.org/core/classes/String.html找到了该方法.

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

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

......但我知道了NoMethodError.

我使用的是Ruby 1.9.1p253,所以我不认为我使用的是旧版本.这是怎么回事?

sco*_*ttd 35

Ruby 1.9不再eachString课堂上了.使用任何一种each_chareach_line取决于您想要做什么.Ruby 1.9的文档Stringhttp://ruby-doc.org/core-1.9.3/String.html.


Pet*_*ter 10

each_char改为使用:

"hello\nworld".each_char {|s| p s}
Run Code Online (Sandbox Code Playgroud)

至于为什么它不工作,它适用于1.8而不是1.9.

  • `String#each`按行迭代,而不是char. (3认同)

Ben*_*Ben 2

在 1.8.7 中工作,没有出现在 1.9 文档中——肯定已经被弃用了。

我们开始吧:https://web.archive.org/web/20090423003136/http ://eigenclass.org/hiki.rb?Changes+in+Ruby+1.9#l113