From: dblack@... Date: 2007-08-04T03:21:43+09:00 Subject: Re: Beginner's tutorial and poor attempt at classes Hi -- On Sat, 4 Aug 2007, Gabriel Dragffy wrote: > > On 2 Aug 2007, at 15:18, dblack@rubypal.com wrote: > >> Hi -- >> >> On Thu, 2 Aug 2007, Gabriel Dragffy wrote: >> >>> Hi all >>> >>> I just started with Ruby (yesterday actually). Have been reading the >>> amazing Poignant Guide, and also a couple of other very basic tutorials. >>> From one of these I wrote an example class, now my knowledge of Ruby has >>> expanded a little I tried to rewrite the class to be even better. I >>> thought that the method "setme" would allow the @numberShowing to be >>> changed to any number between 1 and 6... but obviously not...? >>> >>> >>> #/usr/bin/env ruby >>> >>> class Die >>> def initialize >>> roll >>> end >>> >>> def roll >>> @numberShowing = 1 + rand(6) >>> end >>> def showing >>> @numberShowing >>> end >>> >>> def setme value >>> if value === 1..6 >>> @numberShowing = value >>> else >>> puts "A dice has only six sides!" >>> end >>> end >>> >>> end >> >> You've got the === backwards; you want: >> >> if (1..6) === value >> >> or >> >> if (1..6).include?(value) >> >> Here's a little rewrite, using a reader attribute to streamline the >> retrieval of the die's number: >> >> class Die >> attr_reader :number >> >> def initialize >> roll >> end >> >> def roll >> self.number = rand(6) + 1 >> end > > > Have been rereading your example. Just wanted to ask why in the code just > above did you use "self.number" which you changed from @number? > > >> >> def number=(value) >> if (1..6).include?(value) >> @number = value >> else >> puts "A die has only six sides!" >> end >> end >> end > > and then here "@number" is used.. finding this a little confusing. Thanks > again, for all your help. The number= method does some data checking, and if all is well it sets @number. I don't want to set @number directly, because the checking won't happen. I guess rand(6) + 1 is pretty safe, but still, since my setter method does more than just set @number, it's "polite" to go through that method instead of just setting @number. David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)