1

我为 Enumerables 模块编写了代码:

module Enumerables
  def palindrome?
    if self.is_a?(Hash)
      return false
    else
      self.join('').gsub(/\W/,"").downcase == self.join('').gsub(/\W/,"").downcase.reverse
    end
  end
end

问题是,我必须写这些:

class Array
  include Enumerables
end

class Hash
  include Enumerables
end

使代码成功运行。

有没有一种简单的方法来制作“回文”?方法使用不同的实例类型运行?

4

3 回答 3

3

该模块不是Enumerables,但Enumerable如果你有

module Enumerable
  def palindrome?
    ...
  end
end

它可以在没有包含的情况下工作。

如果您想将此方法添加到所有对象,请参阅 texasbruce 的答案。

于 2012-10-15T23:48:14.617 回答
1

打开对象级别以下的任何类并在其中添加此方法。然后几乎所有内置类型和所有用户定义类型都可以访问它。

你可以把它放在Object, Kernel(它是一个模块), BasicObject.

例如,

class Object
  def foo
    puts "hello"
  end
end
[].foo
于 2012-10-15T23:54:35.547 回答
0

您可以使用带有过滤器的ObjectSpace.each_object迭代器来查找包含 Enumerable 的类并动态扩展它们:

# XXX: this iterator yields *every* object in the interpreter!
ObjectSpace.each_object do |obj|
  if obj.is_a?(Class) && (obj < Enumerable)
    obj.module_eval { include Enumerables }
  end
end

[1,2,1].palindrome? # => true
{}.palindrome? # => false

现在的诀窍是以有意义的方式编写适用于所有可枚举类型的东西!另请注意,这种元编程很有趣,但如果您打算将其用于“玩具”程序以外的任何东西,则会产生严重影响。

于 2012-10-15T23:46:23.680 回答