Ruby - 从块内部更新实例变量

时间:2013-05-28 21:52:33

标签: ruby-2.0 pry

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

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

1 个答案:

答案 0 :(得分: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