Forum: Ruby Included modules and String

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
3b3639fb6a0c490f6292741751000c37?d=identicon&s=25 Rich (Guest)
on 2005-12-28 17:05
(Received via mailing list)
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.

-Rich
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2005-12-28 17:11
(Received via mailing list)
On Dec 28, 2005, at 10:03 AM, Rich wrote:

> Am I misunderstanding how include works in this case?  Thanks alot.
String iterates over lines of text by default, but that's easily
changed:

 >> require "enumerator"
=> true
 >> "12345".enum_for(:each_byte).map { |byte| byte - ?0 }
=> [1, 2, 3, 4, 5]

Hope that helps.

James Edward Gray II
3b3639fb6a0c490f6292741751000c37?d=identicon&s=25 Rich (Guest)
on 2005-12-28 17:32
(Received via mailing list)
Awesome.  Thanks alot.
Fe9b2d0628c0943af374b2fe5b320a82?d=identicon&s=25 Eero Saynatkari (rue)
on 2005-12-28 20:23
Rich wrote:
> 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 :)

> -Rich


E
This topic is locked and can not be replied to.