Sort hash with keys as integer

  • Thread starter PÃ¥l Bergström
  • Start date
P

Pål Bergström

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?
 
Y

Y. NOBUOKA

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 }
 
P

Pål Bergström

Y. NOBUOKA said:
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 :)
 
R

Robert Klemme

2010/9/25 P=E5l Bergstr=F6m said:
Y. NOBUOKA said:
p hash.sort { |a, b| a[0].to_i <=3D> 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" =3D> "test", "2" =3D> "aaa", "10" =3D> "bbb"
}.sort_by {|k,v| k.to_i}
=3D> [["1", "test"], ["2", "aaa"], ["10", "bbb"]]
irb(main):002:0> { "1" =3D> "test", "2" =3D> "aaa", "10" =3D> "bbb"
}.sort_by {|k,v| Integer(k)}
=3D> [["1", "test"], ["2", "aaa"], ["10", "bbb"]]

Cheers

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top