views:

117

answers:

1

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?

+4  A: 

Use define_method:

class Module
  def return_empty_set *names
    names.each do |name|
      define_method(name){Set.new}
    end
  end
end
Marc-André Lafortune
excellent, thanks. and you're right, it should be under `Module`, since then I can `include` this functionality.
Peter
Not sure if that's what you mean, but the reason to put it under `Module` is that you can use it when inside a `Module` definition (to be included later) as well as a `Class`'.
Marc-André Lafortune
yep, that's what I meant.
Peter