From: Robert Klemme Date: 2011-11-14T21:57:42+09:00 Subject: Re: Noob question regarding custom method 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 -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/