Please unsubscribe from this list. Regards, Bharath -----Original Message----- From: Luca (Email) [mailto:luca.pagano / email.it] Sent: Thursday, December 29, 2011 12:22 PM To: ruby-talk ML Subject: I: Noob question regarding custom method -----Messaggio originale----- Da: Junayeed Ahnaf Nirjhor [mailto:zombiegenerator / aol.com] Inviato: luned14 novembre 2011 14:17 A: ruby-talk ML Oggetto: Re: Noob question regarding custom method On 11/14/2011 06:57 PM, Robert Klemme wrote: > On Mon, Nov 14, 2011 at 1:29 PM, Sam Rose<samwho / lbak.co.uk> wrote: >> "setter" methods that have "set" in the name are far more idiomatic >> of Java. Ruby has a different way of doing this: >> >> def miles=(new_miles) >> @miles = new_miles >> end >> >> Which I know wasn't the question, I just felt like mentioning this >> first :) >> >> You're right, you could use attr_accessor (or reader or writer, >> whichever suits the purpose best). And in this case, you probably >> would. There's no reason not to. But some setter methods require, for > example, some kind of validation. >> >> Say if you didn't want the @miles variable to be less than 0, you >> could do this: >> >> def miles=(new_miles) >> if new_miles< 0 >> raise Exception, "Miles cannot be less than 0." >> else >> @miles = new_miles >> end >> end >> >> Is this making sense? :) > Just a stylistic remark: I would code it like this > > def miles=(new_miles) > if new_miles< 0 > raise Exception, "Miles cannot be less than 0." > end > > @miles = new_miles > end > > or even > > def miles=(new_miles) > raise Exception, "Miles cannot be less than 0." if new_miles< 0 > > @miles = new_miles > end > > or > > def miles=(new_miles) > new_miles< 0 and raise Exception, "Miles cannot be less than 0." > > @miles = new_miles > end > > Especially with the first variant it is immediately clear what the > main course of action is. The exception interrupts the regular flow > anyway so there is really no reason for the "else" branch. > > Kind regards > > robert > Thank you robert and sam for answering the question . It helped. -- Junayeed Ahnaf Nirjhor /Doing this and that/ http://twitter.com/nirjhor -- Caselle da 1GB, trasmetti allegati fino a 3GB e in piu' IMAP, POP3 e SMTP autenticato? GRATIS solo con Email.it http://www.email.it/f Sponsor: Capodanno al parco Oltremare Riccione: Pacchetto hotel 3 stelle in centro + ingresso al parco. * Mezza pensione, Internet gratis, animazione per bimbi. Scopri l'offerta! Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid980&d)-12