Included modules and String

R

Rich

I looked at the RDoc for the String class and found that the class
includes the Enumerable module. I'd have thought that meant that you
could call methods like inject or collect on a string, the method
would iterate over all the characters in the string.

However, I get the following instead:
"12345".collect { |x| x.to_i}
=3D=3D> [12345] # instead of the expected [1,2,3,4,5].

Am I misunderstanding how include works in this case? Thanks alot.

-Rich
 
J

James Edward Gray II

I looked at the RDoc for the String class and found that the class
includes the Enumerable module. I'd have thought that meant that you
could call methods like inject or collect on a string, the method
would iterate over all the characters in the string.

However, I get the following instead:
"12345".collect { |x| x.to_i}
==> [12345] # instead of the expected [1,2,3,4,5].

Am I misunderstanding how include works in this case? Thanks alot.

String iterates over lines of text by default, but that's easily
changed:
=> [1, 2, 3, 4, 5]

Hope that helps.

James Edward Gray II
 
E

Eero Saynatkari

Rich said:
I looked at the RDoc for the String class and found that the class
includes the Enumerable module. I'd have thought that meant that you
could call methods like inject or collect on a string, the method
would iterate over all the characters in the string.

However, I get the following instead:
"12345".collect { |x| x.to_i}
==> [12345] # instead of the expected [1,2,3,4,5].

Am I misunderstanding how include works in this case? Thanks alot.

The reason for this is that Enumerable merely wraps the
object's #each method. In the case of String, #each by
default splits the string at each line (as determined
by the record separator constant $/).

Using Enumerator works around this nicely :)


E
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top