简体   繁体   中英

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 hack. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM