就更好的可變範圍和知名度,我會推薦使用區塊。但是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