Created
September 26, 2017 02:52
-
-
Save mactkg/ffb89b9f85a6a4ed41bf068956893a63 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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