0
0

More than 3 years have passed since last update.

【備忘録】tapについて少し調べてみた。

Last updated at Posted at 2020-12-01

環境

Ruby 2.6
Rails 5.1.7

背景

機能実装中、似たような処理を探していたら「tap」を見つけてなんだこれ、と思い調べた。これは初めて遭遇したので備忘録として。

tapとは

"foo".tap {|str| puts str.reverse}
# oof
# => "foo"

メソッドの返り値は変わっておらず小文字のままだけれど、tap自体は動いていて文字列が反対になっている。
調べたところによると、tapはメソッドの中で何かしたいけど、メソッド自体の評価は変えたくない時に使うみたい。

実際に見たコード

こんな使い方もある(らしい)。

...
User.new.tap do |item|
  item.name = "Taro"
  item.address = "test@gmail.com"
  --- 中略 ---
  item.tel_num = "09012345678"
end.save!
...

endの後にsave!ってなんやねんと思ったけど大分スッキリ書けますね。
tapを応用していって可読性の高いコーディングしていきたいと思います。

0
0
1

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