LoginSignup
11
10

More than 5 years have passed since last update.

Ruby でも Optional Chaining がしたいんじゃ〜!

Last updated at Posted at 2014-08-24

もう type = database.first ? database.first.type : nil とかみたいに書くのはつかれたお……。
Swift みたいに type = database.first?.type って書きたいお……。

というわけでなるべくお手軽に実装。
(NilClass で method_missing して nil を返すと Swift の実装に近づくが、確実にデバッグで死ぬのでおすすめしない)

2015/12/09 追記。
Ruby 2.3.0 から safe navigation operator が実装されましたね。(参考

foo = Foo.new
p foo&.hello

ActiveRecord でいえば try! のほうなので、注意は必要ですが標準でサポートされたというのは大きいと思います。


class Object
  def _?
    self
  end
end

class NilClass
  class Ghost < BasicObject
    def method_missing(*argv)
      nil
    end
  end

  def _?
    @@ghost ||= Ghost.new
    @@ghost
  end
end

class Foo
  def hello
    "hello"
  end

  def foo
    Foo.new
  end
end

foo = Foo.new
p foo._?.hello          # => "hello"
p foo._?.foo._?.hello   # => "hello"

foo = nil
p foo._?.hello          # => nil
p foo._?.foo._?.hello   # => nil

オブジェクトを _? でつなげれば、中身があればそのまま返して、nil なら nil を返すぞ!
_ という名前にしてもいいが、 ? をつければなんとなくわかりやすいかもしれない。
実際に使うならもっとまともな名前をつけような!

ActiveSupportのtryとどっちがいいかは一考の余地あり

11
10
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
11
10