87linux
87linux

Reputation: 23

Why can't I attach a singleton method to another object?

some_string = "i love lamp"
another_string = "i love desk"
def some_string.lovehate
    if match /love/
        sub /love/, "hate"
    elsif match /hate/
        sub /hate/, "love"
    end
end

puts some_string.lovehate # => "i hate lamp"
puts another_string.respond_to? :lovehate # => false
m = some_string.method(:lovehate).unbind
m.bind(another_string).call # fails 

This fails with

singleton method called for a different object (TypeError)

So clearly the ruby programmers thought this was a bad idea for some reason. My question is what is stopping me from doing this?

Upvotes: 2

Views: 274

Answers (1)

Chuck
Chuck

Reputation: 237010

This is consistent with how UnboundMethods normally work. The object you bind them to has to be a kind_of? the class the method came from. another_string is not descended from some_string's singleton class (just like no other object is), so you can't bind the the methods of some_string's singleton class to it.

Upvotes: 2

Related Questions