Proc¶
Proc 代表一個函數指標,帶有一個可選的上下文(閉包資料)。它通常使用 proc 字面值建立
# A proc without parameters
->{ 1 } # Proc(Int32)
# A proc with one parameter
->(x : Int32) { x.to_s } # Proc(Int32, String)
# A proc with two parameters
->(x : Int32, y : Int32) { x + y } # Proc(Int32, Int32, Int32)
參數的類型是強制性的,除非直接將 proc 字面值傳送到 C 綁定中的 lib fun
。
回傳類型會從 proc 的主體推斷,但也允許明確提供
# A proc returning an Int32 or String
-> : Int32 | String { 1 } # Proc(Int32 | String)
# A proc with one parameter and returning Nil
->(x : Array(String)) : Nil { x.delete("foo") } # Proc(Array(String), Nil)
# The return type must match the proc's body
->(x : Int32) : Bool { x.to_s } # Error: expected Proc to return Bool, not String
也提供 new
方法,它會從捕獲的區塊建立 Proc
。這種形式主要用於別名
Proc(Int32, String).new { |x| x.to_s } # Proc(Int32, String)
alias Foo = Int32 -> String
Foo.new { |x| x.to_s } # same proc as above
Proc 類型¶
要表示 Proc 類型,您可以寫入
# A Proc accepting a single Int32 argument and returning a String
Proc(Int32, String)
# A proc accepting no arguments and returning Nil
Proc(Nil)
# A proc accepting two arguments (one Int32 and one String) and returning a Char
Proc(Int32, String, Char)
在類型限制、泛型類型引數和預期類型等其他地方,您可以使用較短的語法,如類型中所述
# An array of Proc(Int32, String, Char)
Array(Int32, String -> Char)
調用¶
要調用 Proc,請在其上調用 call
方法。引數的數量必須與 proc 的類型匹配
proc = ->(x : Int32, y : Int32) { x + y }
proc.call(1, 2) # => 3
從方法¶
可以從現有方法建立 Proc
def one
1
end
proc = ->one
proc.call # => 1
如果方法有參數,則必須指定其類型
def plus_one(x)
x + 1
end
proc = ->plus_one(Int32)
proc.call(41) # => 42
proc 可以選擇性地指定接收器
str = "hello"
proc = ->str.count(Char)
proc.call('e') # => 1
proc.call('l') # => 2