Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Object | tap

概要

Object#tap {|x| ... } -> self

詳細

self を引数としてブロックを評価し、self を返却。
メソッドチェインの途中に割り込んで、処理途中の値を表示・確認するのが目的。

サンプルコード
p [*1..5].zip([*?a..?e]).tap { |e|print e.inspect, "\n"}
       .map { |num, alph|num + alph.ord }.tap { |e|print e.inspect, "\n"}
       .map { |e|e.chr }.tap { |e|print e.inspect, "\n"}
       .map { |e|e.ord }.tap { |e|print e.inspect, "\n"}
       .reduce(&:+)

出力

[[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]
[98, 100, 102, 104, 106]
["b", "d", "f", "h", "j"]
[98, 100, 102, 104, 106]
510