Skip to content

Instantly share code, notes, and snippets.

@nagachika
Created May 8, 2019 07:09
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 nagachika/5021bd93cfa97c54fe0a85c2c2fea903 to your computer and use it in GitHub Desktop.
Save nagachika/5021bd93cfa97c54fe0a85c2c2fea903 to your computer and use it in GitHub Desktop.
UnboundMethod example
module M
def foo
puts "deinfed?(foo) => #{defined?(foo).inspect}"
puts "method(:foo) => #{method(:foo) rescue $!}"
p self
end
end
a = "str-a"
a.extend(M)
m = a.method(:foo)
puts "===== m.call ====="
m.call
puts "=========="
ubm = m.unbind
b = "str-b"
puts "===== ubm.bind(b).call ====="
ubm.bind(b).call
puts "=========="
puts "===== ubm.bind(42).call ====="
ubm.bind(42).call
puts "=========="
===== m.call =====
deinfed?(foo) => "method"
method(:foo) => #<Method: "str-a".foo>
"str-a"
==========
===== ubm.bind(b).call =====
deinfed?(foo) => nil
method(:foo) => undefined method `foo' for class `String'
"str-b"
==========
===== ubm.bind(42).call =====
deinfed?(foo) => nil
method(:foo) => undefined method `foo' for class `Integer'
42
==========
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment