03 - blocks as closures - using outside variables within a code block.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 31 行

RB
31
字号
def add_to_all(array, number)  array.collect { |x| x + number }endadd_to_all([1, 2, 3], 10)                # => [11, 12, 13]#---tax_percent = 6position = lambda do  "I have always supported a #{tax_percent}% tax on imported limes."endposition.call# => "I have always supported a 6% tax on imported limes."tax_percent = 7.25position.call # => "I have always supported a 7.25% tax on imported limes."#---counter = 04.times { counter += 1; puts "Counter now #{counter}"}# Counter now 1# Counter now 2# Counter now 3# Counter now 4counter                                                  # => 4#---accumulator = [][1, 2, 3].reverse_each { |x| accumulator << x + 1 }accumulator                  # => [4, 3, 2]#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?