EX. Joe 90, Mike 80, Steve 100.
How would i print out something like below? Is it even possible in Ruby?
Rank Name Score
1 Steve 100
2 Joe 90
3 Mike 80
Any help greatly appreciated!!
EX. Joe 90, Mike 80, Steve 100.
How would i print out something like below? Is it even possible in Ruby?
Rank Name Score
1 Steve 100
2 Joe 90
3 Mike 80
Any help greatly appreciated!!
you can do Iterating over a Ruby Hash using each_with_index
{ steve: 100, jeo: 90,mike: 80 }.each_with_index do |(key, value), index|
puts "#{index}: #{key} => #{value}"
end
As pointed out in the comments, the most intuitive way to solve this problem is to probably have an array of users where each user is represented inside his own hash (which might be what you were referring to in your question).
users = [
{ name: "Joe", score: 90 },
{ name: "Mike", score: 80 },
{ name: "Steve", score: 100 }
]
sorted_users = users.sort_by { |user| user[:score] }.reverse
puts "Rank Name Score"
sorted_users.each_with_index do |user, index|
rank_str = (index + 1).to_s.ljust(7)
name_str = user[:name].ljust(10)
score_str = user[:score].to_s.rjust(5)
puts "#{rank_str}#{name_str}#{score_str}"
end
which will print out the following
# Rank Name Score
# 1 Steve 100
# 2 Joe 90
# 3 Mike 80