在Ruby on Rails中,我如何编写代码来解决这个问题? “编写一个程序,从用户那里获取两个数字,并显示2个数字的总和,差异,乘积和商数”
答案 0 :(得分:1)
创建文件calc.rb
class Calc
def sum(a,b)
a + b
end
def mul(a,b)
a * b
end
def diff(a,b)
a - b
end
def div(a,b)
a / b
end
end
puts "Enter A"
a = gets.chomp.to_i
puts "Enter B"
b = gets.chomp.to_i
obj = Calc.new
p "sum: #{obj.sum(a,b)}"
p "product: #{obj.mul(a,b)}"
p "quotient: #{obj.div(a,b)}"
p "difference: #{obj.diff(a,b)}"
在控制台中运行这个
ruby calc.rb
Enter A
4
Enter B
2
"sum: 6"
"product: 8"
"quotient: 2"
"difference: 2"