我是一名 Ruby 初学者。我对Why's Poignant Guide中的一个例子感到困惑。
我了解以下示例对 in 的使用(也来自 Poignant Guide)picks
,initialize
因为它是作为参数传入的。
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