I thought I'd post these ideas here, since last time I wrote up an RCR and then got told that the issue had already been addressed in plans for Ruby 2. Also, some ideas I'm pretty happy with, some are quite radical/provocative. Hopefully those latter bits are somewhat independent, which ones do you like? (if any
So please let me know if I'm missing something, or this could be done better.
1) Default arguments for &block
Often a method performs some simple reasonably useful behaviour if no block is given, otherwise it lets the block do something more useful. For example:
def transform_values(array)
聽聽out=[] unless block_given?
聽聽array.each { |value|
聽聽聽聽# calculations...
聽聽聽聽if block_given?
聽聽聽聽聽聽yield value,newvalue
聽聽聽聽else
聽聽聽聽聽聽out<< newvalue
聽聽聽聽end
聽聽}
聽聽out
end
I propose &block could take a default argument, probably of the form
&block={|x| foo}, but I could live with &block=proc {|x| foo}.
block_given? would return *false* if the default value was used (I'm flexible on this bit).
The default block would be scoped *inside* the method.
That example would become:
def transform_values(array) &block={|val,newval| out<< newval}
聽聽out=[] unless block_given?
聽聽array.each { |value|
聽聽聽聽#calculations...
聽聽聽聽yield value,newvalue
聽聽}
end
2) Taking anonymous block parameter, making it part of the signature
Two issues:
聽聽聽聽聽a) If block default values are adopted, then giving the block a
聽聽聽聽聽聽聽name might sometimes seem silly, as the name's never used.
聽聽聽聽聽聽聽See the above example, "block" is never referenced.
聽聽b) No way to specify taking a block as part of method signature.
聽聽聽聽聽聽聽Descrptive signatures are good:
聽聽聽聽聽聽聽* See syntax in auto-docs/code without reading whole thing
聽聽聽聽聽聽聽* See syntax in auto-docs/code when there's no comments
聽聽聽聽聽聽聽* Flag errors at start of method, and on every invocation.
Proposal: allow "&" in place of "&block":
def foo & (or maybe: def foo &!)
聽聽As soon as the method is called, raises an error if no block is
聽聽given (similar to wrong number of args)
def foo &? (or maybe: def foo &)
聽聽No change from current behaviour of def foo, but denotes that
聽聽this method can take a block and might use it if given.
(MAYBE:)
def foo &block! or
def foo &!block or
replace current meaning(!) of: def foo &block
聽聽This method is required to take a block, not passing a block
聽聽raises an error.
def foo &block or
def foo &block? or
def foo &?block, etc
聽聽Current meaning of &block.
My preferred syntax in a throw-everything-away-for-Ruby2 scenario:
聽聽聽聽Named block Anonymous block
Disallowed def foo def foo
Optional def foo &block? def foo &?
Defaulted def foo &block={} def foo &={}
Compulsory def foo &block def foo &
My preferred syntax in a backwards-compatible scenario:
聽聽聽聽Named block Anonymous block
Disallowed - -
Optional def foo &block def foo &?
Defaulted def foo &block={} def foo &={}
Compulsory def foo &block! def foo &!
Thoughts?
Sam