Skip to content

Instantly share code, notes, and snippets.

@mactkg
Created September 26, 2017 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mactkg/ffb89b9f85a6a4ed41bf068956893a63 to your computer and use it in GitHub Desktop.
Save mactkg/ffb89b9f85a6a4ed41bf068956893a63 to your computer and use it in GitHub Desktop.
module AddableExtender
def define_adder(*keys)
define_method :+ do |other|
result = keys.map { |key| send(key) + other.send(key) }
self.class.new(*result)
end
end
end
Point = Struct.new(:x, :y) do
extend AddableExtender
define_adder(:x, :y)
# オーバーライドして定義ができない
def +(other)
puts ":+ called"
super(other) #=> `+': super: no superclass method `+' for #<struct Point x=42, y=4> (NoMethodError)
end
end
p Point.new(42, 4) + Point.new(10, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment