For a better understanding of Ruby I decided to recreate the attr_accessor method. Succesfully. I now understand how it works except for one detail regarding Ruby's syntactic sugar. Here's the attr_accessor method I created:
def attr_accessor(*attributes)
attributes.each do |a|
# Create a setter method (obj.name=)
setter = Proc.new do |val|
instance_variable_set("@#{a}", val)
end
# Create a getter method (obj.name)
getter = Proc.new do
instance_variable_get("@#{a}")
end
self.class.send(:define_method, "#{a}=", setter)
self.class.send(:define_method, "#{a}", getter)
end
end
The way I see it, I just defined two methods, obj.name
as getter and obj.name=
as the setter. But when I execute the code in IRB and call obj.name = "A string"
it still works, even though I defined the method without a space!
I know this is just part of the magic that defines Ruby, but what exactly makes this work?