Confirmation required - initialising


#1

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


#2

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


#3

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

#4

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.)


#5

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


#6

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


#7

removed_email_address@domain.invalid 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.


#8

attr_accessor = attr_reader + attr_writer ?


#9

forest wrote:

attr_accessor = attr_reader + attr_writer ?

Yes, exactly.