本文簡要介紹ruby語言中 Proc.prc[params,...]
的用法。
用法
prc[params,...] → obj
(params,...) → obj
別名:call
調用塊,使用接近方法調用語義的東西將塊的參數設置為 params
中的值。返回塊中計算的最後一個表達式的值。
a_proc = Proc.new {|scalar, *values| values.map {|value| value*scalar } }
a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
a_proc[9, 1, 2, 3] #=> [9, 18, 27]
a_proc.(9, 1, 2, 3) #=> [9, 18, 27]
a_proc.yield(9, 1, 2, 3) #=> [9, 18, 27]
請注意,prc.()
使用給定的參數調用 prc.call()
。隱藏“call”是語法糖。
對於使用 lambda
或 ->()
創建的 proc,如果將錯誤數量的參數傳遞給 proc,則會生成錯誤。對於使用 Proc.new
或 Kernel.proc
創建的 procs,額外的參數被靜默丟棄,缺少的參數設置為 nil
。
a_proc = proc {|a,b| [a,b] }
a_proc.call(1) #=> [1, nil]
a_proc = lambda {|a,b| [a,b] }
a_proc.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
另見 Proc#lambda?
。
相關用法
- Ruby Proc.prc ==用法及代碼示例
- Ruby Proc.prc << g用法及代碼示例
- Ruby Proc.prc >>用法及代碼示例
- Ruby Proc.parameters用法及代碼示例
- Ruby Proc.eql?用法及代碼示例
- Ruby Proc.ruby2_keywords用法及代碼示例
- Ruby Proc.new用法及代碼示例
- Ruby Proc.lambda?用法及代碼示例
- Ruby Proc.arity用法及代碼示例
- Ruby Proc.(params,...)用法及代碼示例
- Ruby Proc.curry用法及代碼示例
- Ruby Proc.binding用法及代碼示例
- Ruby Proc.call用法及代碼示例
- Ruby Process.groups用法及代碼示例
- Ruby Process.wait2用法及代碼示例
- Ruby Process.getpgrp用法及代碼示例
- Ruby Process.setproctitle用法及代碼示例
- Ruby Process.setrlimit用法及代碼示例
- Ruby Process.uid用法及代碼示例
- Ruby Process.pid用法及代碼示例
- Ruby Process.detach用法及代碼示例
- Ruby Process.maxgroups用法及代碼示例
- Ruby Process.clock_gettime用法及代碼示例
- Ruby Process.exec用法及代碼示例
- Ruby Process.groups=用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Proc.prc[params,...]。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。