这是代码:
class Person
attr_accessor :id, :name
def initialize(init = {})
init.each do |k, v|
send("#{k}=", v)
end
end
end
people = [
Person.new(:id => 1, :name => "Adam"),
Person.new(:id => 2),
nil,
]
people.map! do |person|
person ||= Person.new(:id => 3, :name => "Some default")
person.name ||= 'Eve'
person
end
binding.pry
这就是我得到的撬动:
[1] pry(main)> people
=> [#<Person:0x007fc2b0afba98 @id=1, @name="Adam">,
#<Person:0x007fc2b0afb930 @id=2, @name="Eve">,
#<Person:0x007fc2b0afb7f0 @id=3, @name="Some default">]
[2] pry(main)> people.first
=> #<Person:0x007fc2b0afba98 @id=1, @name="Adam">
[3] pry(main)> people.second
NoMethodError: undefined method `second' for #<Array:0x007fc2b0afb890>
from (pry):3:in `<main>'
我期待能够访问people.second
和people.second.id
. 这是怎么回事?