Is i) and ii) just two different methods for initialising? i) class Song attr_reader :name, :artist, : end ii) def initialize(foo, blah, haha) @foo = foo @blah = blah @haha = haha end
on 2006-01-06 16:20
on 2006-01-06 16:32
On Jan 6, 2006, at 8:20 AM, John M. wrote: > Is i) and ii) just two different methods for initialising? > > i) > class Song > attr_reader :name, :artist, : > end If you remove the trailing , and :, the above is equivalent to: class Song def name @name end def artist @artist end end No variables are set by this code, so no, it's not a method of initialization. Hope that helps. James Edward G. II
on 2006-01-06 16:35
John M. wrote: > Is i) and ii) just two different methods for initialising? No. > i) > class Song > attr_reader :name, :artist, : > end Creates attr reader methods but does nothing about values. > ii) > def initialize(foo, blah, haha) > @foo = foo > @blah = blah > @haha = haha > end Initializes values but does not create reader methods. You can make your life easier by using Struct: Song = Struct.new(:name, :artist) s1 = Song.new "foo", "bar" Struct will create setters, getters and an appropriate constructor (#initialize) Kind regards robert
on 2006-01-06 16:42
John M. wrote: > @blah = blah > @haha = haha > end No, the first is basically the same as this: (Ignoring the syntax error) class Song def name() return @name end def artist() return @artist end end attr_reader, attr_writer and attr_accessor don't touch the initialize() method at all. They are just for defining getters and setters because instance variables are always private in Ruby. (There's still ways to get at them from the outside even without getters through reflection, but think before doing that.)
on 2006-01-06 17:33
James Edward G. II wrote: > If you remove the trailing , and :, the above is equivalent to: > > class Song > def name > @name > end > def artist > @artist > end > end > Except that rdoc produces different output for each. James -- http://www.ruby-doc.org - Ruby Help & Documentation http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted http://www.rubystuff.com - The Ruby Store for Ruby Stuff http://www.jamesbritt.com - Playing with Better Toys http://www.30secondrule.com - Building Better Tools
on 2006-01-06 23:58
I'm fairly new to Ruby, but aren't Florian's and James' examples identical, besides the syntax? Both achieve the same thing, correct? Doug
on 2006-01-07 05:49
email@example.com wrote: > I'm fairly new to Ruby, but aren't Florian's and James' examples > identical, besides the syntax? Both achieve the same thing, correct? Yup, when there's no return the result of the last executed statement is automatically returned. Just thought it would be good to be explicit in this case.
on 2006-01-07 10:11
attr_accessor = attr_reader + attr_writer ?
on 2006-01-07 14:56
forest wrote: > attr_accessor = attr_reader + attr_writer ? Yes, exactly.