0

Im having trouble sorting a multidimensional array in ruby and can't find any question similar to my problem. I have an array/hash or both? (excuse me as im coming from a c/php/java background and this is my first time using Ruby)

user['shapeshifter'] = {age => '25', country => 'Australia'}
user['user2'] = {age => '29', country => 'Australia'}
user['user3'] = {age => '21', country => 'Russia'}

i want to sort the user array based on age.

2 Answers 2

4

You need a hash of hashes, and ruby 1.9.2 for sorted hashes, IIRC. This was covered in Sort hash by key, return hash in Ruby

Assuming your test case, fixed so it is valid:

user = {}
user['shapeshifter'] = {:age => 25, :country => 'Australia'}
user['user2'] = {:age => 29, :country => 'Australia'}
user['user3'] = {:age => 21, :country => 'Russia'}

All it takes is:

user.sort_by {|key,value| value[:age]}
Sign up to request clarification or add additional context in comments.

4 Comments

i get this error: in sort_by': undefined method <=>' for #<Hash:0x7f0577f16480> (NoMethodError)
@shapeshifter It worked when I tested his example in irb. Like DGM said, you have to have Ruby 1.9.2 or higher.
That was my problem. Sorry new to ruby didn't realise Centos would be a few versions behind. Should have known! Cheers.
Yeah that's an unfortunate problem with the major distors - they seem to think that ruby 1.8 is still current. At this point everyone should be trying to run on 1.9.3 asap.
1

Currently ruby 1.9 has ordered hash but still does not exist reordering function.

You can try sort pairs of arrays and than make a new Hash. Like this

user = {}
user['shapeshifter'] = {:age => '25', :country => 'Australia'}
user['user2'] = {:age => '29', :country => 'Australia'}
user['user3'] = {:age => '21', :country => 'Russia'}

result1 = user.sort { |user1, user2|
  user1[1][:key] <=> user2[1][:key] # user1,2 = [key, value] from hash
}
puts Hash[result1].inspect

or this

result2 = user.sort_by { |user_key, user_val|
  user_val[:key]
}
puts Hash[result2].inspect

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.