[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Accessors: Problem in accessing an attribute of other class

Anukul Singhal

6/2/2008 7:33:00 AM

Hi,

I was practising accessors in ruby and came across the following
problem:

class Music

attr_accessor :song, :artist
def initialize
@song = "This never happened before"
@artist = "Paul McCartney"
end
end

class Sport < Music

attr_reader :player
attr_accessor :game, :gender
def initialize(player)
@player = player
@game = {:game1 => 'Tennis', :game2 => 'Cricket', :game3 => 'F1'}
@gender = {:g1 => 'male, :g2 => 'female'}
end
end

sp = Sport.new('Roger Federer')
puts sp.player => outputs to "Roger Federer"
puts sp.game[:game1] => outputs to "Tennis"
puts sp.gender[:g1] => outputs to "male"
puts sp.song => outputs to "Nil" => I want to access the song attribute
of Music class so that it shows me the output as "This never happened
before"

Can anyone help so that I can access the attributes of other class?

Thanks,
Anukul
--
Posted via http://www.ruby-....

3 Answers

Stefano Crocco

6/2/2008 7:35:00 AM

0

On Monday 02 June 2008, Anukul Singhal wrote:
> Hi,
>
> I was practising accessors in ruby and came across the following
> problem:
>
> class Music
>
> attr_accessor :song, :artist
> def initialize
> @song = "This never happened before"
> @artist = "Paul McCartney"
> end
> end
>
> class Sport < Music
>
> attr_reader :player
> attr_accessor :game, :gender
> def initialize(player)
> @player = player
> @game = {:game1 => 'Tennis', :game2 => 'Cricket', :game3 => 'F1'}
> @gender = {:g1 => 'male, :g2 => 'female'}
> end
> end
>
> sp = Sport.new('Roger Federer')
> puts sp.player => outputs to "Roger Federer"
> puts sp.game[:game1] => outputs to "Tennis"
> puts sp.gender[:g1] => outputs to "male"
> puts sp.song => outputs to "Nil" => I want to access the song attribute
> of Music class so that it shows me the output as "This never happened
> before"
>
> Can anyone help so that I can access the attributes of other class?
>
> Thanks,
> Anukul

You forgot to call super from Sport#initialize.

Stefano


Paul McMahon

6/2/2008 7:42:00 AM

0

Hi Anukul,

Sorry, but your classes don't make any sense. There is no reason for
Sport to inherit from Music. Likewise, Sport shouldn't have the
attributes player, game, and gender. Perhaps you should brush up on
Object Oriented programming before trying to learn ruby.

Paul

Anukul Singhal

6/2/2008 7:55:00 AM

0

Stefano Crocco wrote:
> On Monday 02 June 2008, Anukul Singhal wrote:
>> @artist = "Paul McCartney"
>> @gender = {:g1 => 'male, :g2 => 'female'}
>>
>> Can anyone help so that I can access the attributes of other class?
>>
>> Thanks,
>> Anukul
>
> You forgot to call super from Sport#initialize.
>
> Stefano

Thanks a lot stefano!!
--
Posted via http://www.ruby-....