开发者

Avoiding class_eval in Ruby metaprogramming

I want to have a return_empty_set class method in Ruby, similar to the attr_reader methods. My proposed implementation is

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

and example usage:

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

but resorting to a string seems like quite a h开发者_运维问答ack. Is there a cleaner or better way to write this, perhaps avoiding class_eval? Or is this the best way to go?


Use define_method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜