2
votes

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?

2

2 Answers

2
votes

When the ruby interpreter sees obj.name = "A string, it will ignore the space between name and = and look for a method named name= on your obj.

-1
votes

Never mind, 'A string' is a perfectly good message name, just try

obj.send "A string" # ^_^

You can even use numbers:

o = Object.new
o.define_singleton_method "555" do "kokot" end
o.send "555"