LoginSignup
1
1

More than 5 years have passed since last update.

Object#tryの逆が欲しい

Posted at

レシーバがnilのときになにかしたいのがObject#try

# a.b.c.try(:d)
if a.b.c
  a.b.c.d
else
  nil
end

逆に、レシーバを使ってなにかの処理をした結果がnilのときに、nilじゃなくてレシーバにするのが欲しい。

if a.b.c.test?
  a.b.c.d
else
  a.b.c
end

Object#return(仮名)というのはどうか。

a.b.c.return {|x| x.d if x.test? }
a.b.c.return(:d)
a.b.c.return(:d, if: :test?)

最初のパターンはこんな感じ。

class Object
  def return
    yield(self) || self
  end
end
1
1
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
1
1