Skip to content

Instantly share code, notes, and snippets.

@rchowe
Created August 16, 2011 15:37
Show Gist options
  • Save rchowe/1149378 to your computer and use it in GitHub Desktop.
Save rchowe/1149378 to your computer and use it in GitHub Desktop.
Ruby Dice Roller
def roll expression
return [0] if (/^(?<count>\d+)d(?<sides>\d+)(?:s(?<drop>\d+))?$/i =~ expression ).nil?
Array.new( count.to_i, nil ).
map { (Random.rand sides.to_i) + 1 }.
sort.reverse.
take( count.to_i - drop.to_i )
end
expr = "(#{ARGV.join ' '})"; last = ''
until last == expr
last = expr
expr = expr.sub(/(\d+d\d+(?:s\d+)?)/i) { |expr| roll(expr).inject(:+).to_s }.
sub(/(\d+)([\+\-\*\/])(\d+)/) { |m| m[0].to_i.send m[1].to_s, m[2].to_i }.
sub(/\(\d+\)/) { |n| n[1..-2] }
end
puts expr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment