4

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?

1 Answer 1

8

Use define_method:

class Module
  def return_empty_set *names
    names.each do |name|
      define_method(name){Set.new}
    end
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

excellent, thanks. and you're right, it should be under Module, since then I can include this functionality.
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'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.