我一直在使用Ruby中的计算器来掌握基础知识。我从用户那里得到了他们告诉我操作的输入,然后我用空格('')作为分隔符拆分字符串,并根据字符串包含的操作符,我执行那个操作。我试图让乘法工作先行,但我不能让它工作。除了从字符串到int的转换外,一切正常。
puts "Hey? What's your name?"
user = gets.chomp
user.capitalize!
puts "Operation please"
operation = gets.chomp
operation = operation.split(' ')
answer = 1
operation.each { |var|
next if var == "*"
var.to_i
answer = var*answer
}
puts "The answer is #{answer}, is that right?"
confirm = gets.chomp
答案 0 :(得分:0)
var.to_i
本身并没有改变它所要求的东西。执行此操作的方法通常以爆炸结束(即!
)来表示,尽管有些人不这样做(请参阅评论)。
使用分配:var = var.to_i
。
答案 1 :(得分:0)
你快到了,你只需要将to_i
的结果保存到变量中。如您所见,操作不到位,您必须存储结果:
2.0.0-p648 :003 > a = '3'
=> "3"
2.0.0-p648 :004 > a.to_i
=> 3
2.0.0-p648 :005 > a
=> "3"
2.0.0-p648 :006 > b = a.to_i
=> 3
2.0.0-p648 :007 > b
=> 3
答案 2 :(得分:-1)
尝试一下,我已经尝试过它并且有效!
puts "Hey? What's your name?"
user = gets.chomp
user.capitalize!
puts "Operation please"
operation = gets.chomp
operation = operation.split(' ')
answer = 1
operation.each do |var|
next if var == "*"
answer = (var.to_i * answer)
end
puts "The answer is #{answer}, is that right?"
confirm = gets.chomp