這裏是我的類:未定義的局部變量紅寶石
class Money
def initialize(dollars, quarters, dimes, nickels, pennies)
@coins = [ {:coin => dollars, :price => 100},
{:coin => quarters, :price => 25},
{:coin => dimes, :price => 10},
{:coin => nickels, :price => 5},
{:coin => pennies, :price => 1} ]
end
def count
total = 0.00
coins.each do |coin|
next if coin[:price] == 0
total += coin[:coin] * coin[:price]
end
total/100
end
end
,我喜歡這個測試吧:
money = Money.new(5, 1, 2, 1, 0)
puts "$%.2f" % money.count
我收到一個錯誤:
money.rb:12:in `count': undefined local variable or method `coins' for #<Money:0x2567310> (NameError)
from money.rb:34:in `<main>'
指向行coins.each do |coin|
和我沒有意義,因爲我認爲,如果我以@
前綴一個變量,我可以使用它遍及我的對象的方法(它不會繼承到不同的對象)。
我得到這個工作使用不同的代碼,不會:
@dollar = dollar
@quarter = quarter
...
我initialize
方法(我count
方法是完全不同的),但現在我想創建哈希表的數組,這樣我可以重構我的count
方法。
任何幫助將不勝感激。
哇...我覺得稍微令人目瞪口呆。我總是認爲你不需要在變量名中包含'@'符號,因爲我已經使用了諸如'#{dollars}'這樣的行,並且它工作正常。謝謝你教我這個簡單的錯誤。 – 2013-05-06 07:42:51
@randynewfield很高興我可以幫忙! :) – 2013-05-06 07:43:23
@randynewfield當你爲一個實例變量進行字符串插值時,你不需要使用的是括號。這樣你就可以做這個'「#@ count」' – vgoff 2013-05-06 16:10:34