Sort By Tag: Programming

attr_accessor and ruby object variables

    

    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:

attr_accessor :myvar

This creates the getter and setter methods from the variable, which(by default) look like this:

   def myvar #this is the getter

           @myvar #returns the contents of @myvar

        end

        def 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 

Class Example

        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! 

        end

 end

script/console 

@myExample = Example.new
=> #<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: 

http://www.ruby-doc.org/docs/UsersGuide/rg/accessors.html


Powered_by_amethyst
Archive
Search
Tags
          Databases (1)
          General (2)
          Hosting (1)
          Hulihan Applications (3)
          Programming (1)
          Ruby (2)
          Ruby on Rails (6)
          Servers (1)
          Software (2)
view rss feed
This site is best displayed in FireFox 1.5+, IE 7+, and Opera 9+