When we are defining getter and setter methods for name in the following code:
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
end
what is happening internally? How is Ruby able to take a symbol and match it with a variable?
It uses
instance_variable_getandinstance_variable_setfor that.Update: as Andrew Marshall noted, not exactly. Most ruby core methods are defined in C, but the result is essentially the same.
One could define
attr_accessorand friends as follows:Note that I’ve also used
define_methodhere to define the accessor methods.I recommend that you take a look at some introductory texts about ruby metaprogramming, such as “Don’t Know Metaprogramming In Ruby?”.