Skip to content

Instantly share code, notes, and snippets.

@whiteleaf7
Created August 7, 2014 01:24
Show Gist options
  • Save whiteleaf7/08d0d3df2142c78123fc to your computer and use it in GitHub Desktop.
Save whiteleaf7/08d0d3df2142c78123fc to your computer and use it in GitHub Desktop.
RubyでSwiftのOptionalChainingモドキ
class NilClass
def method_missing(args)
nil
end
end
module Optional
def method_missing(method_name, *args)
if method_name =~ /\?$/
search_name = method_name[0...-1]
if respond_to?(search_name)
__send__(search_name, *args)
else
nil
end
else
super
end
end
end
class Bar
def bar
puts "bar"
end
end
class Foo
include Optional
def foo
puts "foo"
Bar.new
end
end
Foo.new.foo?.bar
p Foo.new.bar?.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment