Alex Rivera | Logout

redefining a single ruby method on a single instance with a lambda

Asked 2009-04-29T15:51:40.700
41

In Ruby, is there a way to redefine a method of a particular instance of a class using a proc? For example:

class Foo
  def bar()
    return "hello"
  end
end

x = Foo.new
y = Foo.new

(Something like):

y.method(:bar) = lambda { return "goodbye" }

x.bar
y.bar

Producing:

hello
goodbye

Thanks.

Edit
Report

1 Answer

32

I'm not sure what version of Ruby this was added in (at least 1.8.7), but there seems to be an even simpler way of doing this:

str1 = "Hello"
str2 = "Goodbye"
def str1.to_spanish
  "Hola"
end
puts str1 # => Hello
puts str1.to_spanish # => Hola
puts str2 # => Goodbye
puts str2.to_spanish # => Throws a NoMethodError

Learnt about this whilst reading the Ruby Koans (about_class_methods.rb lesson). I'm still not entirely sure what the purpose of this is since it seems a bit dangerous to me.

answered 2013-05-19T05:39:42.167

Your Answer