-4

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!!

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 4
    Yes, it's possible. Easy, even; what has been the sticking point so far? – Dave Newton Jan 28 '19 at 19:58
  • This answer might help you : https://stackoverflow.com/a/4266496/6419007. Once you have an array of arrays, it shouldn't be too hard to display the table. If you expect an answer on StackOverflow, it helps a lot to show what you tried, even if it doesn't work yet. – Eric Duminil Jan 28 '19 at 21:07
  • What is the input? Where is the hash? – sawa Jan 29 '19 at 04:25
  • Don't know why you want to use a hash. I'd put the data in an array, sort it by score and output each item with its corresponding 1-based index (hint: `each.with_index(1) { ... }`). However, without further information, it's unclear what your actual problem is. What do you have so far? Show some code, please. – Stefan Jan 29 '19 at 11:16

2 Answers2

0

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
adarsh
  • 306
  • 5
  • 16
0

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
Kalman
  • 8,001
  • 1
  • 27
  • 45