Created
August 16, 2011 15:37
-
-
Save rchowe/1149378 to your computer and use it in GitHub Desktop.
Ruby Dice Roller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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