From: "trans. (T. Onoma)" Date: 2004-10-04T23:08:42+09:00 Subject: Re: Too Many Ways? On Monday 04 October 2004 04:06 am, Brian Candler wrote: > Those semantics would be more consistent with yield and blk.call, and > generally I applaud anything which improves consistency: > > def foo > yield 1 > end > > foo {|a,b| p a,b} # prints 1, nil > > def bar(&blk) > blk.call(1) > end > > bar {|a,b| p a,b} # prints 1, nil Great point! > However I tend towards the other position: that both the above examples > should raise an "incorrect number of arguments" exception. It tends to trap > errors sooner, rather than later. But I don't feel too strongly about which > way it's done; I feel much more strongly that it should be consistent! Agreed. The reason I've gone the other way is b/c of this kind of thing: def ducky_method(a,b,c,d,e) end ... case method(:ducky_method).arity when 5 when 4 when 3 ... What I mean by ducky_method, is one I'm not sure about how it will be defined, as is sometimes the case, especially with singleton methods. It may not be very common, but, in fact, I just did this the other day. > I quite like your suggestion of &blk=nil though. At the moment in Ruby the > presence/absence of a block makes no difference, until you try to 'yield' > when no block is given. In particular, you can pass a block to a method > which doesn't expect one; I've been caught by that before! Yes, I like it _better_ too. But like matz said it would break a good bit of code :( Fortunately going the other direction to achieve consistency doesn't. Albeit, it does lead to "less obvious" errors at times, like you said, but that's an acceptable trade-off to me --in fact it's part of why I choose Ruby over other langs, i.e. duck-typing. > So in an ideal world I'd have > > def foo(a,b) # block forbidden, raise exception if you pass one > def foo(a,b,&c) # block required, raise exception if it's missing > def foo(a,b,&c=nil) # block optional > > That syntax would also allow a 'default block': > > def foo(a,b,&c=proc{|x| $stderr.puts x}) This last should be allowed anyway, me thinks too. T.