Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str.each in Ruby isn't working

Tags:

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?

like image 266
Tom Avatar asked Jan 20 '10 19:01

Tom


People also ask

How do I show a string in Ruby?

To display a string in your program, you can use the print method: print "Let's print out this string." The print method displays the string exactly as written. print 'This is the first string.

What does Each_char do in Ruby?

The each_char in Ruby is used to pass each character that makes a string to a block in Ruby. The block of each_char takes a single parameter which represents characters in a string.

How do you repeat a string in Ruby?

Repeat a character or string N times in Ruby. In Ruby, when the * operator is used with a string on the left hand side and an integer on the right hand side (i.e. string * integer ), it repeats the string as many times as specified by the integer. For example: foo = "quack!" * 3 puts foo # output: "quack!


1 Answers

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.

like image 136
scottd Avatar answered Oct 02 '22 20:10

scottd