min*_*ank 0 ruby expression operators
我是Ruby和编程的新手.我一直在尝试整理一个随机创建数学问题的小脚本并将其解决,但是我在生成随机数学运算符时遇到了麻烦.
我的脚本到目前为止:
num = (1..10).to_a
num1 = num.shuffle[0]
num2 = num.shuffle[0]
op = %w{+ - = /}
op1 = op.sample
puts w = "#{num1} #{op1} #{num2}"
puts "Your answer is:"
answer = gets()
solution = num1 + "what do I put here??" + num2
if answer.to_i == solution
puts "Correct! The answer is #{solution}"
else
puts "Incorrect, the answer is #{solution}"
end
Run Code Online (Sandbox Code Playgroud)
我设法挑选出一个随机运算符,但不能在解决方案中使用它,因为它是一个字符串.
为什么不使用符号,并将其发送到带参数的操作数?
5.send(:+, 10)
Run Code Online (Sandbox Code Playgroud)
例如:
> syms = [:+, :-, :*, :/]
=> [:+, :-, :*, :/]
> num1.send(syms.sample, num2)
=> 50
Run Code Online (Sandbox Code Playgroud)
为什么你sample用于操作,但不是数字?