From: Gabriel Dragffy Date: 2007-08-02T23:31:06+09:00 Subject: Re: Beginner's tutorial and poor attempt at classes 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) Thank you very much, these work a treat! I've got to now ask the inevitable question - why do they work? What difference does it make which side the things being compared are? I'm sure I'll come across the answer myself as I continue to get better with Ruby, but I'd be glad of an explanation sooner :) > > 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 > > def number=(value) > if (1..6).include?(value) > @number = value > else > puts "A die has only six sides!" > end > end > end > > With this, you can do things like: > > die = Die.new > puts die.number > die.roll > puts die.number > die.number = 20 # A die has only six sides! > > You could also make the number= method private, to discourage (though > not entirely prevent, since private doesn't do that) people from > setting the number manually. > An interesting rewrite and no-doubt far superior. I still struggling with trying to identify the differences between self.???, @, and @@. As far as Python goes I'd say I understand most all of Python's ways of dealing with classes, these Ruby ones.... are gonna take some time! Thanks again for your fast and comprehensive reply, it's much appreciated. Gabriel Dragffy gabe@dragffy.com