在定义之前在初始化中使用实例变量

时间:2013-08-08 17:38:36

标签: ruby

我是Ruby初学者。我对Why's Poignant Guide的一个例子感到困惑。

我理解以下示例在picksinitialize的使用(也来自Poignant Guide),因为它是作为参数传递的。

class LotteryTicket

  NUMERIC_RANGE = 1..25

  attr_reader :picks, :purchased

  def initialize( *picks )
    if picks.length != 3
      raise ArgumentError, "three numbers must be picked"
    elsif picks.uniq.length != 3
      raise ArgumentError, "the three picks must be different numbers"
    elsif picks.detect { |p| not NUMERIC_RANGE === p }
      raise ArgumentError, "the three picks must be numbers between 1 and 25"
    end
    @picks = picks
    @purchased = Time.now
  end

end

但是,以下示例中的initialize如何在没有picks作为参数传入的情况下开始使用picks?在这里,传递了note1, note2, note3。如何将其分配给picks

class AnimalLottoTicket

      # A list of valid notes.
      NOTES = [:Ab, :A, :Bb, :B, :C, :Db, :D, :Eb, :E, :F, :Gb, :G]

      # Stores the three picked notes and a purchase date.
      attr_reader :picks, :purchased

      # Creates a new ticket from three chosen notes.  The three notes
      # must be unique notes.
      def initialize( note1, note2, note3 )
        if [note1, note2, note3].uniq!
          raise ArgumentError, "the three picks must be different notes"
        elsif picks.detect { |p| not NOTES.include? p }
          raise ArgumentError, "the three picks must be notes in the chromatic scale."
        end
        @picks = picks
        @purchased = Time.now
      end
end

2 个答案:

答案 0 :(得分:1)

该代码中有错误。当我在irb中运行它时,我得到以下内容:

NoMethodError: undefined method `detect' for nil:NilClass

从2005年开始讨论here。如果你在初始化开始时提出以下内容,你可能会得到他们想要的东西:

picks = [note1, note2, note3]
if picks.uniq!

答案 1 :(得分:0)

这里,picks不是局部变量。这是attr_reader :picks, :purchased定义的方法。该方法调用实例变量@picks的值。因此@picks = picks@picks = @picks相同,后者将其值分配给自身,但这没有任何影响。我认为是由一个不熟悉Ruby的人写的。

相关问题