From: Robert Klemme Date: 2004-11-08T18:28:41+09:00 Subject: Re: value provided for argument with default value - how to check inside method? "Jamis Buck" schrieb im Newsbeitrag news:418BAC7C.2010201@email.byu.edu... > Robert Klemme wrote: > > > But as I said, my main concern is that this introduces a different pattern > > for state access while Ruby has such a pattern already. > > It has, but it breaks down in certain situations. Consider: > > class T > def initialize( &block ) > instance_eval &block > end > def v > @v > end > def v=( x ) > @v = x > end > end > > t = T.new do > v = 5 > end > > Does T#v= get called? Nope. v is interpreted as a local variable. As it > should be--I'm not arguing for it to do otherwise. All I'm saying is > that there are times where it is useful to have the setter be like the > OP requested. There is even code in Ruby's stdlib that does it that way > (tk, for instance). I didn't think of this situation, thanks for the reminder! For the initialization I prefer this idiom: class T DEFAULT_VALUES = { :v => 10 }.freeze def initialize( values = {} ) DEFAULT_VALUES.merge(values).each do |k,v| send("#{k}=",v) end end def v @v end def v=( x ) @v = x end end t = T.new( :v => 5 ) Advantage of this variant over the one with the block is, that you can easily determine which values were provided by the caller. That's more difficult with the block. > Ruby is known for it's position on TMTOWTDI. Let's not discourage people > from exploring these other avenues. If an approach turns out to be > cumbersome, it won't be adopted. If it works well, people will use it. Of course everybody is free to do what they like. My point is, that it might cause hazzle if someone uses a different pattern for something so basic like attribute assignment where there is a well established different pattern for this. While we should not follow conventions slaverishly, conventions are in fact important and do have their benefits. Kind regards robert