From: Robert Klemme Date: 2006-07-09T18:30:09+09:00 Subject: Re: calling a method for an object in a .each block cont./chat william robb wrote: > Robert Klemme wrote: > [ .. snip ..] > > Thanks for the explanation. I am a bit hazy on what is getting returned > and displayed in irb, but the structure of oo is comming clearer. I was > simply returning a string from the #show method, and letting irb do the > actual 'display', which explaned what was happening. Right. >>> Been >>> programming in procedural languages since fortran 77, so this OO stuff >>> is a bit mind bending. But ... I like it! >> Yeah, it took me some while to grasp it when I learned OO (Turbo >> Pascal at that time). But the OO paradigm is much stronger than plain >> procedural code IMHO. >> > > The origional Turbo Pascal? That came on one 5 1/4 inch diskette, the > first IDE I'd ever seen? That wasen't OO, that was stright-up pascal, > no? V 5.5 was OO - I'm not sure whether that was the first OO version. > I guess you could call VBA/Excel OO, I've messed around with that, but > don't like it all that much. OK to scrap out stuff, automate a chart > for a client or something ... but I can't stand all the > 'clickey-clickey' windows interface you have to plow through just to put > in a bit of code. :-)) > But, enough chat. I am really interested in what you are saying below. > I had a vauge notion to do this, but couldn't develop the syntax to > express what I wanted. If you wouldn't mind, I would appreciate an > example or two. > >> You could for example create individual classes for suit, face and >> maybe also for value implementing the enum pattern, so you end up >> having just a single instance for hearts, clubs, face_up, face_down >> etc. # poor mans enum pattern, # for others see the RAA Suit = Struct.new :name class Suit VALUES = [ HEARTS = new("Heart").freeze, CLUBS = new("Clubs").freeze, DIAMONDS = new("Diamonds").freeze, SPADES = new("Spades").freeze, ].freeze def to_s() name end def self.from_string(s) VALUES.detect {|su| s == su.name} end # restrict to the 4 instances created above def self.new(*a,&b) raise "Not allowed" end end Now you can do Suit::HEARTS Suit::VALUES.each {|s| puts s} Suit.from_string "Hearts" etc. And also case x.suit when Suit::HEARTS then puts "doing something with hearts..." when Suit::CLUBS .... end Kind regards robert