【问题标题】:undefined local variable ruby未定义的局部变量 ruby
【发布时间】:2013-04-29 22:29:58
【问题描述】:

这是我的课:

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 方法。

任何帮助将不胜感激。

【问题讨论】:

    标签: ruby class variables scope


    【解决方案1】:

    在您的count() 方法中,将coins 称为@coins。 否则,您创建的变量仅适用于您的方法,而不是引用您在 initialize() 中创建的实例变量

    这样写:

    def count
        total = 0.00
        @coins.each do |coin|
            next if coin[:price] == 0
            total += coin[:coin] * coin[:price]
        end
        total / 100
    end
    

    【讨论】:

    • 哇...我有点傻眼了。我一直认为您不需要在变量名中包含@ 符号,因为我使用了诸如#{dollars} 之类的行并且它有效。谢谢你教我这个简单的错误。
    • @randynewfield 很高兴我能帮上忙! :)
    • @randynewfield 对实例变量进行字符串插值时不需​​要使用括号。这样你就可以做到这一点"#@count"
    【解决方案2】:

    如果创建实例变量(使用@),则必须始终使用@ 引用它。

    def count
      total = 0.00
      @coins.each do |coin| #Here was your error
        next if coin[:price] == 0
        total += coin[:coin] * coin[:price]
      end
      total / 100
    end
    

    【讨论】:

      猜你喜欢
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多