Unintended consequence: string.sort

irb(main):001:0> “hello world”.sort
=> [“hello world”]

(Because Enumerable#sort calls to_a, and String#to_a = [string])

However this is inconsistent with String#each, and almost certainly
never what the user wants. I’d suggest
String.split($/).sort.join($/).

martin

Hi –

On Thu, 5 Jul 2007, Martin DeMello wrote:

irb(main):001:0> “hello world”.sort
=> [“hello world”]

(Because Enumerable#sort calls to_a, and String#to_a = [string])

However this is inconsistent with String#each, and almost certainly
never what the user wants. I’d suggest
String.split($/).sort.join($/).

I don’t think it’s inconsistent with String#each:

“hello world”.each {|x| p x }
“hello world”

If you have multiple lines it will sort that way:

“hello\nworld”.sort
=> [“hello\n”, “world”]

David

This may help U?

irb(main):001:0> “hello world”.split(/|/).sort
=> [" ", “d”, “e”, “h”, “l”, “l”, “l”, “o”, “o”, “r”, “w”]

2007/7/5, [email protected] [email protected]:

On 7/5/07, [email protected] [email protected] wrote:

However this is inconsistent with String#each, and almost certainly

“hello\nworld”.sort
=> [“hello\n”, “world”]

Just to continue, String#to_a != [string] either.
“a\nb\nc\n”.to_a #=> [“a\n”, “b\n”, “c\n”]

David

On 7/5/07, [email protected] [email protected] wrote:

If you have multiple lines it will sort that way:

“hello\nworld”.sort
=> [“hello\n”, “world”]

Huh - I thought I tried that and it didn’t work. Would still be nicer
for it to return a string (since it can), but I agree it’s consistent.

martin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs