class Example定义为:

class Example
  def initialize(test='hey')
    self.class.send(:define_method, :say_hello, lambda { test })
  end
end

Example.new; Example.new我就得到warning: method redefined; discarding old say_hello.我的结论是,这一定是因为它在实际类中定义了一个方法(从语法上讲,这是有意义的).当然,如果Example的方法中有多个具有不同值的实例,这将是灾难性的.

有没有一种方法可以仅从实例内部为类的实例创建方法?

推荐答案

您需要获取对实例的singleton类的引用,该类包含所有特定于实例的内容,并在其上定义方法.在ruby 1.8中,它看起来有点凌乱.(如果你找到更Clean 解决方案,请告诉我!)

Ruby 1.8

class Example
  def initialize(test='hey')
    singleton = class << self; self end
    singleton.send :define_method, :say_hello, lambda { test }
  end
end

然而,Ruby 1.9提供了一种更简单的方法.

Ruby 1.9

class Example
  def initialize(test='hey')
    define_singleton_method :say_hello, lambda { test }
  end
end

Ruby相关问答推荐

在Glade创建的UI中以编程方式填充GtkTreeView

每秒做某事 x 次

如何过滤散列数组以仅获取另一个数组中的键?

如何在 Ruby 中生成一个包含 n 个唯一随机数的列表?

如何判断 Ruby 数组是否包含多个值之一?

Coffeescript 中等效的 Ruby .times

在 Ruby 早期转义 .each { } 迭代

我如何需要特定版本的 ruby​​ gem?

如何通过一组新的给定键更改哈希的所有键

to_a 和 to_ary 有什么区别?

RSpec allow/expec vs expect/and_return

不区分大小写的数组#include?

获取下周一(或一周中的任何一天)的日期的 Ruby 代码

如何在 Ruby 脚本中运行 Rake 任务?

工厂女孩 - 目的是什么?

Ruby - Array#<< 和 Array#push 之间的区别

如何在 Ruby 中向异常消息中添加信息?

Integer 和 Fixnum 有什么区别?

JavaScript Array:获取项目的范围

带有类名的动态类定义