[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Included modules and String

Rich

12/28/2005 4:04:00 PM

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


2 Answers

James Gray

12/28/2005 4:09:00 PM

0

On Dec 28, 2005, at 10:03 AM, 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.

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


Eero Saynatkari

12/28/2005 7:24:00 PM

0

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


--
Posted via http://www.ruby-....