[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Confirmation required - initialising

John Maclean

1/6/2006 2:20:00 PM

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

--
John Maclean
MSc (DIC)
07739 171 531



6 Answers

Robert Klemme

1/6/2006 2:29:00 PM

0

John Maclean 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

James Gray

1/6/2006 2:32:00 PM

0

On Jan 6, 2006, at 8:20 AM, John Maclean 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 Gray II



Florian Groß

1/6/2006 2:41:00 PM

0

james_b

1/6/2006 3:32:00 PM

0

James Edward Gray II wrote:
> On Jan 6, 2006, at 8:20 AM, John Maclean 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
>

Except that rdoc produces different output for each.


James
--

http://www.ru... - Ruby Help & Documentation
http://www.artima.c... - Ruby Code & Style: Writers wanted
http://www.rub... - The Ruby Store for Ruby Stuff
http://www.jame... - Playing with Better Toys
http://www.30seco... - Building Better Tools


doug.pfeffer

1/6/2006 9:58:00 PM

0

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

Florian Groß

1/7/2006 3:49:00 AM

0