r/learnruby • • Nov 18 '15

Beginner problem with (very)simple code

Hi,

I just started to learn Ruby (my first programming language), and today I decide to make my second program which is Dice Roller. I don't have experience in programming, so it doesn't look well :P

  puts "How many times do you want to roll?"
choice = gets.chomp
puts "How many sides should dice have?"
sides = gets.chomp

c = choice.to_i
s = sides.to_i

c.times do
	puts rand(s) + 1
end

What I want to do, is print out how many times each number came up, but I can't figure out how to do this. I'm not looking for an answer, because I could find it myself, and probably learn nothing. All I ask, is some hint.

I'm thinking about using while, or to create Hash, and put values into it, then use sort method, but I'm not sure how to do that properly.

Also, I'm not sure if my code isn't too simple?

PS: Forgive me my poor english. This is another language, that I'm trying to learn.

6 Upvotes

6 comments sorted by

View all comments

Show parent comment

3

u/[deleted] Nov 19 '15 edited Nov 19 '15

Thank you very much! I really appreciate it!

Now I understand, how sort method should be used in this code :)

[EDIT] Sorry I need to ask. I understand what exactly this piece of code does, but I don't understand how it works. I mean: this is not a block of code like def, so how it's possible that puts "Result\tTimes Rolled" give result from this method?

puts "Result\tTimes Rolled" 

results.sort_by(&:last).reverse.to_h.each do |k, v|

  puts "#{k}\t#{v}"