I am in the Console environment busy reading all the rows from a table into a variable and I noticed that you can reference the results by specifing my_object.id OR my_object[:id].
Can someone tell me if there is a specific reason for this? Is one of these ‘methods’ deprecated or what is the reason for this?
Here is a code snippit: (assuming all has been set)
my_object = MyModel.find(:all)
my_object[1].id #returns => 'my value'
my_object[1][:id] # also returns => 'my value'
Which of these methods are best practice? Or is it purely a notation preference?
you should use
“id” is an instance method generated by rails in the MyModel class and it has its corresponding “id=” setter instance method (yes, it’s a method)
in the other hand
will access the @attributes hash directly:
def read_attribute(attr_name) attr_name = attr_name.to_s if !(value = @attributes[attr_name]).nil? ...... endI’d like you to see this code
If you see the signature of the [] method maybe you’d think that you can call the method like this:
but you can’t do that because Ruby makes some trickery behind the scenes to make it appear just like if you were accessing a normal array (just like php, js, etc does it), don’t get confused.