# Dice roller in Ruby (mainly for D&D)

I have been working with Ruby for about a week or two now, and I wanted to create a dice-rolling application that intakes any string (e.g. 1d4 + 1 or 3d20 + 4) and outputs the correct dice rolling.

def roll(amount = 0, sides = 0)
#this is the function that gets a random roll with the amount of sides and the amount of dice inputted.
srand
total = 0
(amount.to_i).times do
total += rand(1..sides.to_i)
end
end

while true
raw_input = gets.chomp.to_s
if raw_input == "exit"
abort("May your rolls be ever natural.")
end
proc_input = raw_input.tr("^0-9", " ")
#this keeps all the numbers from the string input.
output = proc_input.split()
if (output[2]) == nil
mod = 0
else
mod = output[2]
end
fin = roll(output[0], output[1]) + mod.to_i
puts "#{fin.to_s}"
end


Nice code overall, pretty readable, though there is space for improvements.

1) You don't have to return from ruby methods.

2) Good use of Enumerable methods will make code cleaner.

3) Use loop instead of while true

4) Also consider keyword arguments, as calling roll(2, 4) looks kind of cryptic.

Will all that in mind, we can turn your code into something like:

def roll(amount = 0, sides = 0)
# rand(1..0) will return nil btw
amount.to_i.times.sum { |t| rand(1..sides.to_i) }
end

loop do
input = gets.chomp.to_s

abort("May your rolls be ever natural.") if input == "exit"

amount, sides, mod = input.tr("^0-9", " ").split
fin = roll(amount, sides) + mod.to_i # nil converts to 0

puts fin
end

• Thank you! I looked back at the code, and some of my past projects and realized that I had written it like C or Java, instead of using a more powerful language's syntax and rules. Thanks again. – cricketts Jan 18 '18 at 5:27