2014-01-05 27 views
0

我試圖號碼添加到一個變量,然後顯示變量,但是變量只是保持不變:(下面的代碼...紅寶石變量不會增加或減少

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

它只是顯示了50依舊。有人可以幫忙嗎?

+1

我建議你做你幫個忙,併爲自己節省很多麻煩,如果你將需要半天時間,讀取之一的介紹章節那裏有很多好書嗎? – pjs

回答

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 
+0

謝謝:)現在你說,我記得在 – user3059932

+1

之前看到它就像這樣放在方法名和左括號之間不要放一個空格。因爲馬茨這麼說。 –

+0

@SergioTulentsev謝謝先生......我沒有注意到..修正。 –

1

就其本身而言,只有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
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 
+1

在Ruby中不使用''//作爲註釋指示符語法。使用'#'。 –

0
cash + 5 

在上面的代碼中你總結5到現金,但結果是丟棄。實際上,右側沒有任何分配。

cash = cash + 5 

將產生期望的結果。在這種情況下,您還可以使用shortand

cash += 5