I have problems with sorting a hash. I get this sort 1,10,2,3… Must
be because the key is a string, right? How do I deal with this? How do I
make the key value into an integer?
I have problems with sorting a hash. I get this sort 1,10,2,3…
Must be because the key is a string, right?
I think that your idea is right, but I can’t conclude it.
Please show us your code.
How do I deal with this? How do I
make the key value into an integer?
Using String#to_i method [
class String - RDoc Documentation ],
you can convert a String object to a Integer object.
For instance:
you want to sort this hash
hash = { “1” => “test”, “2” => “aaa”, “10” => “bbb” }
sort : not expectation
p hash.sort { |a, b| a[0] <=> b[0] }
sort : expectation
p hash.sort { |a, b| a[0].to_i <=> b[0].to_i }
Y. NOBUOKA wrote:
p hash.sort { |a, b| a[0].to_i <=> b[0].to_i }
I tried this myself but it didn’t work. Now it did. Strange. Must have
done something wrong before. Thanks 
2010/9/25 Pål Bergström [email protected]:
Y. NOBUOKA wrote:
p hash.sort { |a, b| a[0].to_i <=> b[0].to_i }
I tried this myself but it didn’t work. Now it did. Strange. Must have
done something wrong before. Thanks
This also works:
irb(main):001:0> { “1” => “test”, “2” => “aaa”, “10” => “bbb”
}.sort_by {|k,v| k.to_i}
=> [[“1”, “test”], [“2”, “aaa”], [“10”, “bbb”]]
irb(main):002:0> { “1” => “test”, “2” => “aaa”, “10” => “bbb”
}.sort_by {|k,v| Integer(k)}
=> [[“1”, “test”], [“2”, “aaa”], [“10”, “bbb”]]
Cheers
robert