Write a function that accepts string as a parameter, returning evaluated value of expression in dice notation, including addition and multiplication.
To
Ruby, 87 characters, uses eval
Here's my Ruby solution, partially based on the OP's. It's five characters shorter and only uses eval
once.
def f s
eval s.gsub(/(\d+)?[dD](\d+)/){n=$1?$1.to_i: 1;n.times{n+=rand $2.to_i};n}
end
A readable version of the code:
def f s
eval (s.gsub /(\d+)?[dD](\d+)/ do
n = $1 ? $1.to_i : 1
n.times { n += rand $2.to_i }
n
end)
end