What is attr_accessor?

C

Christopher Swasey

[Note: parts of this message were removed to make it a legal post.]

I even don't know what attr_accessor is.


#attr_accessor is a method of Module.
http://ruby-doc.org/core/classes/Module.html

Perhaps you might want to pickup a copy of the pickaxe book (
http://www.pragprog.com/titles/ruby/programming-ruby). It will firmly ground
you in the fundamentals of the language.

(attr_accessor, by the way, simply defines setter and getter methods for
each symbol passed as a parameter)

Christopher
 
P

Phillip Gawlowski

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

tenxian wrote:
| I even don't know what attr_accessor is.

There is this wonderful thing called 'search engine', which helps in
answering questions:

http://www.google.com/search?client=safari&rls=en&q=ruby attr_accessor&ie=UTF-8&oe=UTF-8

In short: attr_accessor is shorthand to define getters and setters.

For example:

attr_accessor :my_variable creates the methods to assign and to read the
instance variable '@my_variable'. Which saves you from defining these
methods yourself.

- --
Phillip Gawlowski
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com

~ Well, it just seemed wrong to cheat on an ethics test. -- Calvin
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgYBroACgkQbtAgaoJTgL95FgCgjSEHqzPTfgNJybsKzqNMnp51
9tgAnjPFMLHhpXHOAe5hQDJsx8VTbxU3
=kdo5
-----END PGP SIGNATURE-----
 
7

7stud --

tenxian said:
I even don't know what attr_accessor is.

class Dog

def initialize(a_name)
@name = a_name
end

def name #get the name
return @name
end

def name=(a_name) #set the name
@name = a_name
end

end


d = Dog.new("Spot")
puts d.name #Spot

d.name = "Red"
puts d.name #Red


======compare to: ============

class Dog
attr_accessor :name

def initialize(a_name)
@name = a_name
end

end


d = Dog.new("Spot")
puts d.name #Spot

d.name = "Red"
puts d.name #Red
 
M

Marc Heiler

I even don't know what attr_accessor is.

attr_accessor :colour in your class would allow you do to this:


class Dog
attr_accessor :colour
end


jimmy = Dog.new
jimmy.colour = 'brown'

puts jimmy.colour # "brown"
jimmy.colour = 'black'

puts jimmy.colour # "black"



As far as i know the name attr_accessor is chosen because it unites both
attr_reader (getter method) and attr_writer (setter method). (There also
exists attr :foo but I never use attr )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top