Optional block arguments?

V

Vincent Foley

How can I have a block that optionally takes an argument? Thanks.

Vincent.
 
Z

zdennis

Vincent said:
How can I have a block that optionally takes an argument? Thanks.

This has been involved in a recent discussion for how-to handle true anonymous functions in ruby.
Currently you can't do this with proc or Procs, the same way you can with methods. A workaround is
to use *args, since it will capture any/all parameters passed to the method and put them in an array:

irb(main):013:0> pr = proc { |*args| args.length }
=> #<Proc:0xb7c8f154@(irb):13>
irb(main):014:0> pr.call
=> 0
irb(main):015:0> pr.call "hey"
=> 1
irb(main):016:0> pr.call [ 1,2,3 ]
=> 1
irb(main):017:0> pr.call [ 1,2,3 ], :key=>'val', :key2=>'val2'
=> 2

Zach
 
R

Ryan Leavengood

How can I have a block that optionally takes an argument? Thanks.

irb(main):001:0> p =3D proc do |*a|
irb(main):002:1* if a[0]
irb(main):003:2> puts "Got parameter: #{a[0]}"
irb(main):004:2> else
irb(main):005:2* puts "No parameter"
irb(main):006:2> end
irb(main):007:1> end
=3D> #<Proc:0x02b5d640@(irb):1>
irb(main):008:0> p.call
No parameter
=3D> nil
irb(main):009:0> p.call 1
Got parameter: 1
=3D> nil

Ryan
 
D

David A. Black

Hi --

How can I have a block that optionally takes an argument? Thanks.

irb(main):001:0> p = proc do |*a|
irb(main):002:1* if a[0]

I think you'd have to use a.size since with "if a[0]" you'll get false
positives if the first arg is nil or false.


David
 
S

Sean O'Halpin

How can I have a block that optionally takes an argument? Thanks.

Vincent.
I seem to remember Ara Howard recently answered this with an idiom
something like this (apologies to Ara if I've remembered incorrectly):

block =3D proc{|*args|
a, b =3D *args
a ||=3D 1
b ||=3D 2
p [a, b]
}

block.call
block.call(99)
block.call(99, 100)

__END__
[1, 2]
[99, 2]
[99, 100]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,539
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top