0

如何从块内更新实例变量?

例如

def initialize_people(people)
    people.each do |person|
        person = "Bob" if person.nil?
    end 
end

@first = "Adam"
@second = "Eve"
@third = nil

people = [@first, @second, @third]
initialize_people(people)       
puts people

# outputs 
# Adam
# Eve

# would like it to output
# Adam
# Eve
# Bob
4

1 回答 1

0

表达方式:

people.each |person|

在本地定义person到循环。因此,您的循环所做的所有事情都是将本地范围设置person为. 你可以这样做:Bobnil

def initialize_people(people)
    people.each_with_index do |person, i|
        people[i] = "Bob" if person.nil?
    end 
end

或更短:

i = people.find_index(nil)
people[i] = "Bob" if i
于 2013-05-28T21:56:39.847 回答