Okay, this is probably a dumb question, but how do I declare an
optional block parameter with a default value?
I tried several variations on this basic theme:
def meth(&block = lambda { |i| ... })
...
end
But I keep getting syntax errors. Help?
The &block thing is a special dispensation from Ruby, letting you grab
the block but not serving as a normal argument. The way I've always
seen this done is:
def meth(&block)
block ||= lambda { ... }
...
end
I don't think there's a way to do it inside the arglist.
David
···
On Thu, 5 Jan 2006, Mark J.Reed wrote:
--
David A. Black
dblack@wobblini.net
"Ruby for Rails", from Manning Publications, coming April 2006!
> Okay, this is probably a dumb question, but how do I declare an
> optional block parameter with a default value?
>
> I tried several variations on this basic theme:
>
> def meth(&block = lambda { |i| ... })
> ...
> end
The &block thing is a special dispensation from Ruby, letting you grab
the block but not serving as a normal argument. The way I've always
seen this done is:
def meth(&block)
block ||= lambda { ... }
...
end
But keep in mind that assigning to block inside the method doesn't
affect the behavior of yield:
def test(&block)
block ||= lambda{ puts "default" }
yield
end
=> nil
test
LocalJumpError: no block given
So if you need a default block and currently use yield, you'll either
need to branch on block_given? (as suggested by James), or just use
block.call instead of yield. The latter is probably preferrable, but
may have subtle differences in parameter assignment if it matters.
Jacob Fugal
···
On 1/4/06, dblack@wobblini.net <dblack@wobblini.net> wrote:
On 1/4/06, dblack@wobblini.net <dblack@wobblini.net> wrote:
On Thu, 5 Jan 2006, Mark J.Reed wrote:
Okay, this is probably a dumb question, but how do I declare an
optional block parameter with a default value?
I tried several variations on this basic theme:
def meth(&block = lambda { |i| ... })
...
end
The &block thing is a special dispensation from Ruby, letting you grab
the block but not serving as a normal argument. The way I've always
seen this done is:
def meth(&block)
block ||= lambda { ... }
...
end
But keep in mind that assigning to block inside the method doesn't
affect the behavior of yield:
> def test(&block)
> block ||= lambda{ puts "default" }
> yield
> end
=> nil
> test
LocalJumpError: no block given
Right -- all that happens in my version is assignment to a variable.
David
--
David A. Black
dblack@wobblini.net
"Ruby for Rails", from Manning Publications, coming April 2006!
Thanks to all who posted. The upshot seems to be that I need to declare
the method with no block in the signature, and then check block_given?
within the body and manually invoke a default block if none was passed in.
Which is basically the solution I arrived at, although I had forgotten about
block_given? and was trapping the LocalJumpError to achieve the same result.