Ruby变量不会加或减

时间:2014-01-05 11:43:30

标签: ruby variables counting

我正在尝试向变量添加数字然后显示变量,但变量保持不变:(这是代码......

cash = 50  
puts "You have #{cash} dollars"
sleep (2)
cash + 5
puts "You have #{cash} dollars"

它只显示为50。有人可以帮忙吗?

4 个答案:

答案 0 :(得分:2)

将其写为cash = cash + 5,您将获得所需的输出。cash + 5创建新的Fixnum实例55,但您没有分配对象的引用55到局部变量cash。看下面:

cash = 50  
puts "You have #{cash} dollars"
sleep(2) # or you can write as sleep 2
cash = cash + 5
puts "You have #{cash} dollars"
# >> You have 50 dollars
# >> You have 55 dollars

现在,如果您不想cash = cash + 5,请执行以下操作:

cash = 50  
puts "You have #{cash} dollars"
sleep(2) # or you can write as sleep 2
puts "You have #{cash+5} dollars"
# >> You have 50 dollars
# >> You have 55 dollars

答案 1 :(得分:2)

单独cash + 5 输出评估 - 在您的情况下,您希望输出分配给cash

cash = 50                       # Declare the `cash` variable
#=> 50 

puts "You have #{cash} dollars" # Print the value of `cash`
#=> You have 50 dollars

cash + 5                        # Print the value of (`cash` + 5) WITHOUT assigning it
#=> 55

puts "You have #{cash} dollars" # Print the value of `cash`
#=> You have 50 dollars

cash = cash + 5                 # Assign the returned value of (`cash` + 5) to `cash`
#=> 55

puts "You have #{cash} dollars" # Print the value of `cash`
#=> You have 55 dollars

答案 2 :(得分:2)

cash = 50  
puts "You have #{cash} dollars"
sleep (2)
cash + 5   # this just returns 55 in ruby. For example you could have newVar = cash + 5 , newVar would equal 55 but cash still would equal 50
puts "You have #{cash} dollars"

要获得所需的金额,请执行以下操作。 每次添加到变量的最常见方式是这样的

cash += 5

这是

的简写
cash = cash + 5

答案 3 :(得分:0)

cash + 5

在上面的代码中,您将5加到现金,但结果将被丢弃。事实上,右边没有作业。

cash = cash + 5

将产生所需的结果。在这种情况下,您还可以使用短和

cash += 5