0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Procオブジェクトをブロックの代わりに渡す

Posted at

Procオブジェクトはブロックと同じように「処理の塊」を表しますが、ブロックとは異なり、オブジェクトとして扱うことができます。つまり、変数に入れて別のメソッドに渡したり、Procオブジェクトに対してメソッドを呼び出したりすることができるわけです。

「引数のblockはメソッド実行時に紐づけられたブロックである」と説明しました。その説明にもう一言付け加えるなら、「引数のblockはProcオブジェクトである」と言うこともできます。

まずはブロックを書いてみる

irb(main):001* def greeing(&block)
irb(main):002*   puts 'おはよう'
irb(main):003*   text = block.call('こんにちは')
irb(main):004*   puts text
irb(main):005*   puts 'こんばんは'
irb(main):006> end
=> :greeing

引数のブロックはProcオブジェクト

irb(main):001* def greeting(&block)
irb(main):002*   puts block.class
irb(main):003*
irb(main):004*   puts 'おはよう'
irb(main):005*   text = block.call('こんにちは')
irb(main):006*   puts text
irb(main):007*   puts 'こんばんは'
irb(main):008> end
=> :greeting
irb(main):009* greeting do |text|
irb(main):010*   text * 2
irb(main):011> end
Proc
おはよう
こんにちはこんにちは
こんばんは
=> nil

Procオブジェクトを変数に使うことよって行を短くできる

irb(main):002* def greeting(&block)
irb(main):003*   puts 'おはよう'
irb(main):004*   text = block.call('こんにちは')
irb(main):005*   puts text
irb(main):006*   puts 'こんばんは'
irb(main):007> end
=> :greeting
irb(main):008> repeat_proc = Proc.new{ |text| text * 2 } # block.call('こんにちは')が二回実施される
=> #<Proc:0x000000010e0a3a70 (irb):8>
irb(main):009> greeting(&repeat_proc)
おはよう
こんにちはこんにちは
こんばんは
=> nil

  • ブロックをオブジェクト化できると変数にもできるのか

変数名は関係ない

irb(main):020> repeat_proc = Proc.new{ |bl| bl * 2 }
=> #<Proc:0x000000011215af78 (irb):20>
irb(main):021> greeting(&repeat_proc)
おはよう
こんにちはこんにちは
こんばんは
=> nil

irb(main):009> repeat_proc = Proc.new{ |block| block * 2 }
=> #<Proc:0x000000010a657768 (irb):9>
irb(main):010> greeting(&repeat_proc)
おはよう
こんにちはこんにちは
こんばんは
=> nil

ブロック処理が二回行われる

irb(main):002* def greeting(&block)
irb(main):003*   puts 'おはよう'
irb(main):004*   text = block.call('こんにちは')
irb(main):005*   puts text
irb(main):006*   puts 'こんばんは'
irb(main):007> end
irb(main):009> repeat_proc = Proc.new{ |block| block * 2 }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?