Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
def define_singleton_method_by_proc(obj, name, block)
  metaclass = class << obj; self; end
  metaclass.send(:define_method, name, block)
end
p = proc { "foobar!" }
define_singleton_method_by_proc(y, :bar, p)

or, if you want to monkey-patch Object to make it easy

class Object
  # note that this method is already defined in Ruby 1.9
  def define_singleton_method(name, callable = nil, &block)
    block ||= callable
    metaclass = class << self; self; end
    metaclass.send(:define_method, name, block)
  end
end

p = proc { "foobar!" }
y.define_singleton_method(:bar, p)
#or
y.define_singleton_method(:bar) do
   "foobar!"
end

or, if you want to define your proc inline, this may be more readable

class << y
  define_method(:bar, proc { "foobar!" })
end

or,

class << y
  define_method(:bar) { "foobar!" }
end

this is the most readable, but probably doesn't fit your needs

def y.bar
  "goodbye"
end

This question is highly related


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...