如何从块内更新实例变量?
E.g。
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
答案 0 :(得分:0)
表达式:
people.each |person|
在循环中本地定义person
。因此,当发现person
时,您所做的所有循环都设置为本地范围Bob
到nil
。你可以这样做:
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