Avoiding class_eval in Ruby metaprogramming
- by Peter
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?