Skip to content

Instantly share code, notes, and snippets.

@kl
Last active August 29, 2015 14:02
Show Gist options
  • Save kl/8bb92fb2baa6de0ef114 to your computer and use it in GitHub Desktop.
Save kl/8bb92fb2baa6de0ef114 to your computer and use it in GitHub Desktop.
Hacking the Groovy Safe Navigation Operator in Ruby
class Object
# Given a method name that ends with ¤ call the method name without ¤.
# If the method (excluding ¤) is not found call BasicObject#method_missing,
# unless self is nil, in which case nil is returned.
#
# If the original method is the single character "¤" and self is nil,
# return the first argument. This is the "Elvis" operator.
#
# Examples:
#
# p %w[array of words].reverse[2].upcase¤.slice¤(0, 3)
# => "ARR"
#
# p %w[array of words].reverse[99].upcase¤.slice¤(0, 3)
# => nil
#
# p %w[array of words].reverse[99].upcase¤.slice¤(0, 3) .¤ :default
# => :default
#
def method_missing(name, *args, &block)
return super unless name[-1] == "¤"
return args.first if name.size == 1 && self == nil # "Elvis" operator
method = name.to_s.chop.to_sym
if self == nil && !respond_to?(method)
nil
elsif respond_to?(method)
send(method, *args, &block)
else
super(method, *args, &block)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment