ruby - 使用 lambda 在单个实例上重新定义单个 ruby​​ 方法

标签 ruby oop

在 Ruby 中,有没有办法使用 proc 重新定义类的特定实例的方法?例如:

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

x = Foo.new
y = Foo.new

(类似的东西):

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

x.bar
y.bar

制作:

hello
goodbye

谢谢。

最佳答案

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)

或者,如果你想猴子修补对象以使其变得容易

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

或者,如果你想定义你的 proc 内联,这可能更具可读性

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

或者,

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

这是最易读的,但可能不符合您的需求

def y.bar
  "goodbye"
end

This question is highly related

关于ruby - 使用 lambda 在单个实例上重新定义单个 ruby​​ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/803020/

相关文章:

c# - 一个无法访问的类。 VS2010

oop - 什么是 "upcast"?

ruby - block 中的局部变量

ruby - rspec - 如何改变 lambda 应该期望的?

ruby-on-rails - 对于具有大量 "realtime"页面更新(来自 Rails 背景)的网站,可以使用什么工具?

html - Ruby on Rails - 创建 #Show 的自定义路由

ios - 从 Xcode cocoapods 插件运行 pod install

PHP继承的父方法无法访问 child 的私有(private)属性(property)

c++ - 写入特定数据成员的内存时出错

ios - 创建 MVC 的 Model 类的最佳实践