就更好的可变范围和知名度,我会推荐使用区块。但是lambda是一个完美的解决方案,如果你只是想存储和执行。
从我的理解,我想你想访问my_first_array在command_store之外的某处。所以你的情况这将是:
情景我:如果你不希望暴露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
方案II:假设你想赋值语句是有效的外部变量。在这种情况下考虑使用绑定也是一个好主意。
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
这正是Lambda和块用于。 – texasbruce 2012-08-03 09:29:13