这让我很困惑:
class Person
attr_accessor :id, :name
def initialize(init)
init.each_pair do |key, val|
instance_variable_set('@' + key.to_s, val)
end
end
end
@adam = Person.new(:id => 1, :name => "Adam")
@eve = Person.new(:id => 2)
@people = [ @adam, @eve, nil ]
print @people
@people.map! do |person|
person ||= Person.new(:id => 3, :name => "Some default")
if person.name.nil?
person.name = "Eve"
end
end
print @people
# outputs
# [#<Person:0x007ff184303900 @id=1, @name="Adam">, #<Person:0x007ff184303770 @id=2>, nil]
# [nil, "Some default", "Some default"]
我想完全填充@people,以便最终得到以下内容:
[#<Person:0x007ff184303900 @id=1, @name="Adam">, #<Person:0x007ff184303770 @id=2, @name="Eve">, #<Person:0x007ff184301111 @id=3, @name="Some default">]
我究竟做错了什么?