I even don't know what attr_accessor is.
on 2008-04-30 07:33
On Wed, Apr 30, 2008 at 1:25 AM, tenxian <hi.steven.tu@gmail.com> wrote: > 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
on 2008-04-30 07:43
-----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&... 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-----
on 2008-04-30 08:44
tenxian wrote:
> 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
on 2008-04-30 17:25
> 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 )
Please log in before posting. Registration is free and takes only a minute.
Existing account
(Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
Log in with Google account | Log in with Yahoo account
No account? Register here.