Forum: Ruby Sort hash with keys as integer

3275da7fdbd73cb4e7956fd0d29164de?d=identicon&s=25 Paul Bergstrom (palb)
on 2010-09-25 15:23
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?
Bc1be7710a977bbb55ff45990853a4ec?d=identicon&s=25 Y. NOBUOKA (Guest)
on 2010-09-25 15:59
(Received via mailing list)
> 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 [
http://ruby-doc.org/core/classes/String.html#M000787 ],
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 }
3275da7fdbd73cb4e7956fd0d29164de?d=identicon&s=25 Paul Bergstrom (palb)
on 2010-09-25 16:10
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 :-)
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2010-09-26 22:03
(Received via mailing list)
2010/9/25 Pål Bergström <pal@palbergstrom.com>:
> 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
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.