Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
John Steer-Fowler
Courses Plus Student 11,734 PointsAccessing an Array of Hashes - Can anyone help?
I am currently creating a Ruby program and have run into an issue that I am unable to solve.
I have an array of hashes that holds a lot of the information in my program. For example:
array = [{ name: "Jack", gender: "Male", age: 30 }, { name: "Wendy", gender: "Female", age: 42 }, { name: "Julie", gender: "Female", age: 29 }]
I know that I can access the individual hashes like so:
array.each do |person|
puts person[:age]
end
What I am trying to achieve is to find out which value of the 'age' key is the highest, and then assign that age to a variable called 'highest_age'
I have been trying something like this:
age = array.select { |person| person[:age] }
highest_age = age.max
This is not working for me. Can anybody help at all? Would appreciate any help.
The result should be that the 'highest_age' variable contains the integer 42 as that is the highest age of the three ages I have in my array.
Thanks in advance
Jason Seifer - would appreciate your help if no one else can help.
3 Answers

Sam Shiffman
7,466 PointsHi John, You can access the youngest person with this:
oldest = array.max_by {|person| person[:age]}
=> {:name=>"Wendy", :gender=>"Female", :age=>42}
But to access the value of the :age key, use this:
highest_age = array.max_by do |person| person[:age] end[:age]
=> 42

Sam Shiffman
7,466 PointsJohn, I realized I had labeled that first snipped "youngest", rather than oldest. I also edited my answer to yield the final answer 42. Refresh the page and it should come up.
John Steer-Fowler
Courses Plus Student 11,734 PointsI guessed you meant 'oldest', so don't worry :D
Thank you Sam. I would like to buy you a drink :P

Sam Shiffman
7,466 PointsLook me up next time you're in Portland, OR
John Steer-Fowler
Courses Plus Student 11,734 Points:D will do Sam
John Steer-Fowler
Courses Plus Student 11,734 PointsJohn Steer-Fowler
Courses Plus Student 11,734 PointsSam, what has taken me 3 hours of tinkering you have solved in 20 seconds...
Thank you kind sir :D and thank you max_by Enumerable!