【问题标题】:Ruby: update attribute of an objectRuby:更新对象的属性
【发布时间】:2014-08-03 22:23:24
【问题描述】:

我在 Ruby 中有这两个类:

Prod.rb

class Prod
  attr_reader :code, :price
  def initialize code, price
    @code = code
    @price = price
  end
end

购买.rb

class Buy
  def initialize()
    @items = []
  end

  def addToBasket item
    @items << item
  end

  def changePrice
      @items.each do |item|
        item.price = 0.00
      end
  end
end

当我使用下面的代码测试应用程序时,我收到指向上面item.price = 0.00 的错误:

test_1(MyTest): NoMethodError: undefined method 'price=' for #<Prod:0x24d76e8>

我可以打印 item.price 的值,但无法更新它。有什么想法吗?

MyTest.rb

def setup
    @prod1 = Prod.new("1", 19.95)
  end

  def test_1
    b = Buy.new()
    b.addToBasket(@prod1)
    [...]
  end

【问题讨论】:

    标签: ruby ruby-on-rails-3 pass-by-reference


    【解决方案1】:

    这是因为您没有在类Prod 中定义price= 方法。你只用attr_reader :code, :price 定义了一个getter。如果您要同时创建 getter 和 setter,请在 Prod 类中使用 attr_accessor

    class Prod
      attr_accessor :code, :price
      def initialize code, price
        @code = code
        @price = price
      end
    end
    

    您可以在我的文章中了解有关 ruby​​ 中的 getter 和 setter 的更多信息:Ruby for Admins: Objects

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 2020-07-16
      • 2012-03-16
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多