コンテンツへスキップ

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)

Cバインディングで lib fun に proc リテラルを直接送信する場合を除き、パラメータの型は必須です。

戻り値の型は 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

キャプチャされたブロックから Proc を作成する new メソッドも提供されています。この形式は主にエイリアスで役立ちます

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