0
0

More than 5 years have passed since last update.

【Ruby2.5】yield_selfとtapを使ったサンプルコード

Last updated at Posted at 2019-04-25

yield_selfとtapをサンプルコードで比較

githubにもアップしました。

Kernel#yield_self

レシーバを引数として与えられたブロックを呼び出し、ブロックの評価結果を返す。
tapと似ているが、tapはレシーバ自身を返す。

Object#tap

ブロック変数にレシーバ自身を入れてブロックを実行します。戻り値はレシーバ自身です。

yield_self_vs_tap.rb
### まずは単体で
10.yield_self { |x| x ** 2 }
# 100

10.tap { |x| x ** 2 }
# 10

### 繋げてみる
10.yield_self { |x| x ** 2 }.yield_self { |y| y * 2 }
# 200

10.tap { |x| x ** 2 }.tap { |y| y * 2 }
# 10

### yield_selfとtapの組み合わせ
10.yield_self { |x| x ** 2 }.tap { |y| y * 2 }
# 100

10.tap { |x| x ** 2 }.yield_self { |y| y * 2 }
# 20

参考

技術評論社 『WEB+DB PRESS Vol.103』 p.50
Rubyリファレンス url: https://ref.xaio.jp/ruby

0
0
2

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