Skip to content

Instantly share code, notes, and snippets.

@equivalent
Last active August 29, 2015 14:26
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 equivalent/621e63629185283ffb5b to your computer and use it in GitHub Desktop.
Save equivalent/621e63629185283ffb5b to your computer and use it in GitHub Desktop.
Rebind module method example
# run me with ruby >= 2.0
module A
def x(arg)
"hi #{arg}"
end
end
module B
def x(arg)
"cooool #{arg}"
end
end
class Awesome
attr_accessor :woodoo
def be_awesome(name)
woodoo.bind(self).call(name)
end
end
a = Awesome.new
a.woodoo = A.instance_method(:x)
result = a.be_awesome("tomas")
puts result
a.woodoo = B.instance_method(:x)
result = a.be_awesome("tomas")
puts result
# If you run this with Ruby >= 2.0
# You should see this on your screen:
#
# hi tomas
# cooool tomas
#
# you cannot bind class instance methods
# unless they are from the same ancestory chain:
#
class A
def x(arg)
"hi #{arg}"
end
end
class Awesome < A
attr_accessor :woodoo
def be_awesome(name)
woodoo.bind(self).call(name)
end
def x(arg)
"hi #{arg}"
end
end
a = Awesome.new
a.woodoo = A.instance_method(:x)
a.be_awesome("tomas")
# => "hi tomas"