Ruby 2.1.0在实例变量具有默认值后重新分配

时间:2014-01-31 03:16:29

标签: ruby rspec attr-accessor

我刚刚在过去一个月内学习过Ruby,并且正在研究RSpec的TDD技能。

我正在尝试通过以下测试:

    it "has a modified color" do
    @phone.color = "green"

    puts @phone.color.should == "green"
end

这是我的代码:

    class Phone

      attr_reader   :name
      attr_reader   :manufacturer
      attr_accessor :color

      def initialize(name, manufacturer)
        @name           = name
        @manufacturer   = manufacturer
      end

      def color(color='black')
        @color = color
      end
    end

我试图做以下几点:

    phone = Phone.new("Moto X", "Motorola")
    puts phone.color # 'black'
    phone.color = "green"
    puts phone.color # 'green'

然而,在我尝试将颜色重新分配为绿色后仍然输出“黑色”,请帮忙。

感谢。

1 个答案:

答案 0 :(得分:2)

问题是您的def color是属性读者而不是编写者。因此,它将始终根据参数返回默认颜色black

执行作业时:

phone.color = "green"

它正在调用隐式编写器(由attr_accessor :color生成)。属性编写器看起来像:

def color=(c)
  @color = c
end

将颜色写为“绿色”后,您尝试通过以下方式访问:

puts phone.color

这将执行属性读取器:

def color(c='black')
  @color=c
end

将颜色设置为“黑色”并返回该颜色。

如果您想要默认的黑色,可以像这样定义您的类:

class Phone
  attr_reader   :name
  attr_reader   :manufacturer
  attr_accessor :color         # This generates your reader and writer methods

  def initialize(name, manufacturer)
    @name           = name
    @manufacturer   = manufacturer
  end

  def color
    @color || 'black'    # If @color is nil, return 'black', otherwise @color
  end
end

2.0.0-p195 :012 > phone = Phone.new("Moto X", "Motorola")
 => #<Phone:0x9ecc1ac @name="Moto X", @manufacturer="Motorola">
2.0.0-p195 :013 > phone.color
 => "black"
2.0.0-p195 :014 > phone.color = "green"
 => "green"
2.0.0-p195 :015 > phone.color
 => "green"