1

我在过去一个月内刚刚学习了 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'

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

谢谢。

4

1 回答 1

2

问题是您def color是属性reader而不是writer。因此,它将始终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"
于 2014-01-31T04:09:08.823 回答