0

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

我了解以下示例对 in 的使用(也来自 Poignant Guide)picksinitialize因为它是作为参数传入的。

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但是在下面的例子中,如何在pickspicks作为参数传入的情况下开始使用呢?在这里,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
4

2 回答 2

1

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

NoMethodError: undefined method `detect' for nil:NilClass

这里有一个 2005 年的讨论。如果您在初始化的开头放置以下内容,您可能会得到他们正在寻找的内容:

picks = [note1, note2, note3]
if picks.uniq!
于 2013-08-08T18:16:05.280 回答
0

这里,picks不是局部变量。它是由 定义的方法attr_reader :picks, :purchased。该方法调用实例变量的值@picks。So@picks = picks与 相同@picks = @picks,将其值分配给自身,没有任何效果。我认为是由不熟悉 Ruby 的人编写的。

于 2013-08-08T17:48:43.060 回答