Tom Werner
8/9/2007 8:03:00 PM
dblack@rubypal.com wrote:
> Hi --
>
> On Fri, 10 Aug 2007, Tom Werner wrote:
>
>> Gordon Thiesfeld wrote:
>>> On Aug 9, 11:40 am, Emmanuel Oga <oga_emmanuel_...@yahoo.com.ar>
>>> wrote:
>>>
>>>> how can i use define_method to assign default parameters?
>>>>
>>>>
>>>
>>> Not sure if this is the most elegant way, but:
>>>
>>> define_method(:method_name) do |*args|
>>> parameter, parameter2 = *args
>>> parameter2 ||= 'default'
>>> puts parameter
>>> puts parameter2
>>> end
>>>
>>>
>>>
>>
>>
>> Has the addition of block argument defaults to the language been
>> considered?
>
> Yes, quite often :-)
>
>> There are a number of places (especially in define_method, Proc.new,
>> and lambda) where it would come in handy. The syntax would of course be:
>>
>> def foo
>> yield 'from method'
>> end
>>
>> foo do |x, y = 'from default'|
>> puts x
>> puts y
>> end
>>
>> Which would output:
>>
>> from method
>> from default
>>
>> I've seen this come up enough that its addition would seem welcome.
>> Are there arguments against it?
>
> The problem is with something like:
>
> m do |a, b = 1 | 2 | 3; end
>
> you can't tell which | is doing what.
>
>
> David
>
That's never stopped Ruby from doing other things on a single line.
Single line 'if' statements need a 'then' or a semicolon (being syntax
errors otherwise).
if x | y; 'foo'; end
Or consider the following single line:
x = 10 - 5 - 2
Perfectly valid, but wait! What I really meant was:
x = 10 - 5; -2
The onus is on the programmer to write code that works in the face of
possibly ambiguous syntax.
Simply require a semicolon in your example case and there's no more problem:
m do |a, b = 1|; 2 | 3; end
or
m do |a, b = 1 | 2|; 3; end
Just because a certain functionality *might* produce ambiguous code
seems a poor reason to exclude it from consideration!
Tom