# 使用 lambda

>> def some(lda)
>>     puts "some 1"
>>     lda.call
>>     puts "some 2"
>> end
=> nil
>> lda = lambda { puts "執行 lambda"; return 1 }
=> #<Proc:0x2161320@(irb):38 (lambda)>
>> some(lda)
some 1

some 2
=> nil
>>

def some
def lda
puts "執行 lambda"
return 1
end
puts "some 1"
lda
puts "some 2"
end

>> lda = lambda { puts "執行 lambda"; return 1 }
=> #<Proc:0x2161320@(irb):38 (lambda)>

lambda與 直接使用Proc.new建立的物件不同的地方在於，Proc.new直接建立的物件像個程式流程，而lambda方法建立的Proc物件像是個方法，因 此lambda建立時的程式區塊return，就像是個方法return，另外，lambda建立的Proc物件，有哪些區塊參數，call就只能傳入幾 個引數。例如：
>> l = lambda { |a, b| puts a, b }
=> #<Proc:0x27fffa8@(irb):17 (lambda)>
>> l.call(1, 2)

1
2
=> nil
>> l.call(1)

ArgumentError: wrong number of arguments (1 for 2)
from (irb):17:in `block in irb_binding'
from (irb):19:in `call'
from (irb):19
from C:/Winware/Ruby192/bin/irb:12:in `<main>'
>> l.call(1, 2, 3)

ArgumentError: wrong number of arguments (3 for 2)
from (irb):17:in `block in irb_binding'
from (irb):20:in `call'
from (irb):20
from C:/Winware/Ruby192/bin/irb:12:in `<main>'
>>

>> l = ->(a, b) { puts a, b }
=> #<Proc:0x2468880@(irb):21 (lambda)>
>> l.call(10, 20)
10
20
=> nil
>>

>> [1, 2, 3].each(&->(element) { puts element })
1
2
3
=> [1, 2, 3]
>>

``# encoding: Big5class Range    def comprehend(&block)        return self if block.nil?        self.collect(&block).compact    endenddef prepare_factor(max)    prime = Array.new(max, 1)    2.upto(Math.sqrt(max).to_i - 1) do |i|        if prime[i] == 1            (2 * i).upto(max - 1) do |j|                if j % i == 0                    prime[j] = 0                end            end        end    end        primes = (2..max - 1).comprehend { |i| i if prime[i] == 1} # 質數表    ->(num) {        list = []        i = 0        while primes[i] ** 2 <= num            if num % primes[i] == 0                list << primes[i]                num /= primes[i]            else                i += 1            end        end        list << num        f = Array.new(list.length, 0)        f.length.times { |i|            f[i] = list[i]        }        return f # 在這邊return是可以不寫的，只是為了強調    }endfactor = prepare_factor(1000)p factor.call(100)  # 顯示 [2, 2, 5, 5]p factor.call(500)  # 顯示 [2, 2, 5, 5, 5]p factor.call(800)  # 顯示 [2, 2, 2, 2, 2, 5, 5]``

def prepare_factor(max)
...
Proc.new { |num|
list = []
i = 0
while primes[i] ** 2 <= num
if num % primes[i] == 0
list << primes[i]
num /= primes[i]
else
i += 1
end
end
list << num
f = Array.new(list.length, 0)
f.length.times { |i|
f[i] = list[i]
}
f
}
end