I am looking for way to create the according attr_reader methods while setting the values for the according instance variables in the initialize method? For example, the following code:
class SomeClass
attr_reader :hello
def initialize( arg)
@hello = arg
end
end
I am looking for way to write as follows:
class SomeClass
def initialize( arg)
some_method_as_described_in_question( @hello, arg)
end
end
Does a method doing what I have described exist in the Ruby built-in Classes and Modules?
You can open the eigenclass from within the method and set the attribute there:
That way each instance’s eigenclass will have that attribute reader. But really it only makes sense to do things that way if the attribute name is dynamic, and can vary from instance to instance. If it’s always
hello, I don’t see any drawback to just defining it in the class like your original code block.For example, if you are dynamically passing in the attribute name, you could do it like this:
This is compatible with Ruby 1.8. Taking a tip from @HenrikN in the comment to your question, you can use
define_singleton_methodin Ruby 1.9: