Robert Klemme
1/2/2007 4:55:00 PM
On 02.01.2007 17:20, Florian Gross wrote:
> Peter Lynch wrote:
>
>> I would like to know if a function has been called with or without an
>> optional argument.
>
> Not very pretty:
But clever!
> def fun(a, b = (no_b = true; 5))
> if no_b then
> "Fun(%p): %p" % [a, b]
> else
> "Fun(%p, %p)" % [a, b]
> end
> end
>
> fun(1) # => "Fun(1): 5"
> fun(1, 2) # => "Fun(1, 2)"
The only other reasonable alternative I can see is this:
def fun(a,*bb)
if bb.empty?
puts "no b"
else
puts "b=#{b}"
end
end
Note that the other approach that has been mentioned cannot reliably
detect whether the parameter was set or not:
def fun(a,b=nil)
if b.nil?
puts "no b"
else
puts "b=#{b}"
end
end
irb(main):013:0> fun 1
no b
=> nil
irb(main):014:0> fun 1,2
b=2
=> nil
irb(main):015:0> fun 1,nil
no b
=> nil
(The last one should have printed "b=".)
You get more options if you want to use named parameters (i.e. a Hash):
def fun(args={})
a = args[:a]
b = args[:b]
if args.has_key? :b
puts "b=#{b}"
else
puts "no b"
end
end
irb(main):053:0> fun(:a=>1)
no b
=> nil
irb(main):054:0> fun(:a=>1, :b=>2)
b=2
=> nil
irb(main):055:0> fun(:b=>2)
b=2
=> nil
Kind regards
robert