Sort hash with keys as 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? 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 [
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 }

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 :slight_smile:

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 :slight_smile:

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

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