ruby - 在 Ruby 元编程中避免使用 class_eval

标签 ruby metaprogramming

我想在 Ruby 中有一个 return_empty_set 类方法,类似于 attr_reader 方法。我建议的实现是

class Class
  def return_empty_set *list
    list.each do |x|
      class_eval "def #{x}; Set.new; end"
    end
  end
end

和示例用法:

class Foo
  return_empty_set :one
end
Foo.new.one  # returns #<Set: {}>

但是求助于字符串似乎是个 hack。是否有更简洁或更好的方式来编写此代码,或许可以避免 class_eval?或者这是最好的方法吗?

最佳答案

使用define_method:

class Module
  def return_empty_set *names
    names.each do |name|
      define_method(name){Set.new}
    end
  end
end

关于ruby - 在 Ruby 元编程中避免使用 class_eval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2889283/

相关文章:

c++ - 在模板特化中使用非类型模板模板参数

ruby-on-rails - rvm 更新 : Your local changes to the following files would be overwritten by merge on rvm get head command 上的 git 错误

ruby - ruby 是否支持递归枚举器?

R:创建自定义错误消息,为包中的函数提供参数值

python - 如何在 PyCharm 中使用元编程支持动态类型提示?

c++ - 如何从/向 boost MSM 状态机交换数据

ruby - 打包字符串以包含空字节

ruby-on-rails - 有选择地将选项传递给另一个方法

Ruby File.read 与 File.gets

perl - 在 Perl5 中实现功能切换