"".to_a isn't consistent with "string".to_a

C

Clifford Heath

I've just been tripped up by this behaviour, which I haven't
seen documented anywhere:

"hello".to_a #=> ["hello"]
"".to_a #=> []

Why does an empty string get omitted from the array?
Why doesn't Enumerable#to_a document this behaviour of strings?
This is completely broken (Ruby 1.8.6)

This affected me in a call to send() using a splat - it always
works ok except when the parameter list is an empty string :-(.

Clifford Heath.
 
C

Christopher Swasey

I've just been tripped up by this behaviour, which I haven't
seen documented anywhere:

"hello".to_a #=> ["hello"]
"".to_a #=> []

Why does an empty string get omitted from the array?
Why doesn't Enumerable#to_a document this behaviour of strings?
This is completely broken (Ruby 1.8.6)

I disagree. #to_a doesn't just encase the string object in an
otherwise empty array, rather it casts the string to an array, as
appropriate:

"".to_a => []
"test".to_a => ["test"]
"this\nis\na\n\test".to_a => ["this\n", "is\n", "a\n", "test"]

The array equivalent of an empty string is an empty array. Both, for
instance, have a #size of 0.

Christopher
 
J

Joel VanderWerf

Christopher said:
I've just been tripped up by this behaviour, which I haven't
seen documented anywhere:

"hello".to_a #=> ["hello"]
"".to_a #=> []

Why does an empty string get omitted from the array?
Why doesn't Enumerable#to_a document this behaviour of strings?
This is completely broken (Ruby 1.8.6)

I disagree. #to_a doesn't just encase the string object in an
otherwise empty array, rather it casts the string to an array, as
appropriate:

"".to_a => []
"test".to_a => ["test"]
"this\nis\na\n\test".to_a => ["this\n", "is\n", "a\n", "test"]

The array equivalent of an empty string is an empty array. Both, for
instance, have a #size of 0.

To add to that: the way I've understood it is that, in the context of a
String, the Enumerable methods treat it as an enumeration of lines.
 
C

Clifford Heath

Joel said:
To add to that: the way I've understood it is that, in the context of a
String, the Enumerable methods treat it as an enumeration of lines.

Right, that does make sense now, thanks folk.
Enumerable is built on #each, and String#each does that.

Clifford Heath.
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top