就更好的变量范围和可见性而言,我建议使用块。但是如果你只想存储和执行,lambda是一个完美的解决方案。
据我了解,我猜您想在 command_store 之外的某个地方访问 my_first_array。因此,在您的情况下,它将是:
场景一:如果您不想公开 my_first_array,但仍想以某种方式使用它。
def command_store
puts 'Hello World'
# here my_first_array is just a local variable inside command_store
my_first_array = Array.new(5) {|i| Random.rand(100)}
yield(my_first_array)
puts 'Hello World again'
end
command_store() do |x|
# puts '**Call from outside'
puts "The first element is #{x[0]}"
# ...
puts "The last element is #{x[-1]}"
# puts '**Call from outside again'
end
# Output:
# => Hello World
# => The first element is 41
# => The last element is 76
# => Hello World again
场景二:假设您希望赋值语句对外部变量有效。在这种情况下考虑使用绑定也是一个好主意。
def command_store(var=[])
puts 'Hello World'
# here my_first_array is just a local variable inside command_store
my_first_array = Array.new(5) {|i| Random.rand(100)}
var.replace(my_first_array)
puts 'Hello World again'
return var
end
a = Array.new
command_store(a)
puts a[0]
b = command_store()
puts b[0]
# Output:
# => Hello World
# => Hello World again
# => 66
# => Hello World
# => Hello World again
# => 16