23

I'm Learning Ruby.

I found the method String#each at http://ruby-doc.org/core/classes/String.html.

When I try using it...

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

...but I get that NoMethodError.

I'm using Ruby 1.9.1p253 so I don't think I'm using an old version. What's going on?

Veger
  • 37,240
  • 11
  • 105
  • 116
Tom
  • 231
  • 1
  • 2
  • 3

4 Answers4

37

Ruby 1.9 no longer has each on the String class. Use either each_char or each_line depending on what you want to do. The docs for Ruby 1.9 String are http://ruby-doc.org/core-1.9.3/String.html.

mmoya
  • 1,901
  • 1
  • 21
  • 30
scottd
  • 7,364
  • 1
  • 24
  • 27
10

Use each_char instead:

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

as to why it's not working, it works in 1.8 but not 1.9.

Peter
  • 127,331
  • 53
  • 180
  • 211
3

You're looking at the docs for 1.8. String#each has been removed in 1.9. Use each_line instead.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
2

Works in 1.8.7, doesn't show up in the 1.9 docs -- must have been deprecated.

Here we go: https://web.archive.org/web/20090423003136/http://eigenclass.org/hiki.rb?Changes+in+Ruby+1.9#l113

jotik
  • 17,044
  • 13
  • 58
  • 123
Ben
  • 6,857
  • 26
  • 23