In most other languages(java, c++, etc.), when you create an object, you have to define the variables that will make up the structure of the object. You also usually add a getter(retrieves the variable) and a setter(sets/writes the contents of the variable) so you can access the variable.
However, in Ruby, you only need one line of code that will do all of the above:
This creates the getter and setter methods from the variable, which(by default) look like this:
@myvar #returns the contents of @myvar
enddef myvar(anything) #this is the setter
@myvar = anything #set the contents of myvar to anything!
end
You're also looking at the code to override the methods, too! Example: If you want to create a backup variable whenever you create the original, do this:
app/model/example.rb
attr_accessor :myvar
def myvar=(anything) #this is the setter
@myvar_backup = @myvar #backup the original variable
@myvar = anything #set the contents of myvar to anything!
endend
script/console
=> #<Example:0x2b50b2c3d560>
>> @myExample.inspect # see what the object has
=> "#<Example:0x2b50b2c3d560>"
>> @myExample.myvar = "hello!" # set the variable
=> "hello!"
>> @myExample.inspect # see what the object has now
=> "#<Example:0x2b50b2c3d560 @myvar_backup=\"hello!\", @myvar=\"hello!\">"
Also, if you just wanted the getter or setter only, you would use:
attr_reader :myvar or attr_writer :myvar
Read more about accessors:


