From: Junayeed Ahnaf Nirjhor Date: 2011-11-14T22:17:24+09:00 Subject: Re: Noob question regarding custom method --------------080903030602070801090409 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit On 11/14/2011 06:57 PM, Robert Klemme wrote: > On Mon, Nov 14, 2011 at 1:29 PM, Sam Rose 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 --------------080903030602070801090409--