Avoiding class_eval in Ruby metaprogramming

Posted by Peter on Stack Overflow See other posts from Stack Overflow or by Peter
Published on 2010-05-22T18:36:16Z Indexed on 2010/05/22 18:40 UTC
Read the original article Hit count: 244

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about metaprogramming