Confirmation required - initialising

J

John Maclean

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
 
R

Robert Klemme

John said:
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
 
J

James Edward Gray II

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 Gray II
 
F

Florian Groß

John said:
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

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

James Britt

D

doug.pfeffer

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
 
F

Florian Groß

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.
 

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,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top