Skip to content

Instantly share code, notes, and snippets.

@nagachika
Created May 8, 2019 07:09

Revisions

  1. nagachika created this gist May 8, 2019.
    26 changes: 26 additions & 0 deletions unbound-method-example.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    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 "=========="
    15 changes: 15 additions & 0 deletions z-result.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    ===== 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
    ==========