views:

78

answers:

3

In Ruby 1.8.7, Array("hello\nhello") gives you ["hello\n", "hello"]. This does two things that I don't expect:

  1. It splits the string on newlines. I'd expect it simply to give me an array with the string I pass in as its single element without modifying the data I pass in.

  2. Even if you accept that it's reasonable to split a string when passing it to Array, why does it retain the newline character when "foo\nbar".split does not?

Additionally:

>> Array.[] "foo\nbar"
=> ["foo\nbar"]
>> Array.[] *"foo\nbar"
=> ["foo\n", "bar"]
A: 

If you replace the double-quotes with single-quotes it works as expected:

>> Array.[] "foo\nbar"
=> ["foo\nbar"]
>> Array.[] 'foo\nbar'
=> ["foo\\nbar"]
fahadsadah
No, actually, that means the newline is not interpreted at all.
Shtééf
Which is what Tyson wanted, though it doesn't answer the why.
fahadsadah
A: 

You may try:

"foo\nbar".split(/w/)
"foo\nbar".split(/^/)
"foo\nbar".split(/$/)

and other regular expressions.

kovrik
+1  A: 

It splits the string on newlines. I'd expect it simply to give me an array with the string I pass in as its single element without modifying the data I pass in.

That's a convention as good as any other. For example, the list constructor in Python does something entirely different:

>>> list("foo")
['f', 'o', 'o']

So long as it's consistent I don't see the problem.

Even if you accept that it's reasonable to split a string when passing it to Array, why does it retain the newline character when "foo\nbar".split does not?

My wild guess here (supported by quick googling and TryRuby) is that the .split method for strings does so to make it the "inverse" operation of the .join method for arrays.

>> "foospambar".split("spam").join("spam")
=> "foospambar"

By the way, I cannot replicate your behaviour on TryRuby:

>> x = Array("foo\nbar")                                                         
=> ["foo\nbar"]   
>> Array.[] *"foo\nbar"                                                 
=> ["foo\nbar"]   
badp