From: James Britt Date: 2006-12-24T10:46:29+09:00 Subject: Re: Beginner issues Anime Junkie wrote: > Hello all, > > I'm not much of a developer but will be supporting RoR in the near > future and thought I would familiarize myself with Ruby a bit. I'm > using the "Programming Ruby" book and find that a lot of the examples > don't work. They use too much pseudo code in my opinion. Anyhow, could > anyone explain why the following doesn't work? I've put comments in > where I thought necessary. > > class Song > > attr_reader :duration > > def initialize(duration) > @duration = duration > end > > def duration_in_mins=(new_duration) > @duration = (new_duration*60).to_i > end > > end # End Song > > song = Song.new(360) > > puts song.duration # this prints 360 > > song.duration_in_mins = 2 > > puts song.duration # this prints out 120 > > puts song.duration_in_mins # I assumed that this would print 2 but > produces the error "undefined method `duration_in_mins'" > > //I know that duration_in_mins is a virtual attribute but if I can use > it for assigning value shouldn't I be able to print that? > The notion of "virtual attribute" is confusing at best. In Ruby, communication with objects is done via messages (usually these map to methods). Object data are stored in instance variables, which are private to the instance, duration_in_mins=(arg) is a method. It assigns a value to the instance variable @duration. To get at the value of an instance variable, from outside of that instance, you need a method that returns that value. The call attr_reader :duration defines such a method for you. It's a bit of Ruby metaprogramming that generates a method at runtime. But the code (so far) has no definition for the method 'duration_in_mins', so you get an exception. -- James Britt http://www.ruby-doc.org - Ruby Help & Documentation http://www.rubystuff.com - The Ruby Store for Ruby Stuff http://beginningruby.com - Beginning Ruby: The Online Book