def method(a, b=0)but this isn't:
#...
end
Proc.new {|a, b=0| } ### syntax error!See e.g. this discussion in Ruby forum.
However it is possible to simulate the behaviour, creating a de facto signature with default values. For example lets say I want a proc accepting the same parameters as a method defined as
def a(b, c=1)
:lambda do |*args| # simulated signature: |b, c=1|This has the disadvantage that is not validating the number of arguments, so let's add some validation code to the block:
b, c = args[0], args[1] || 1
end
lambda do |*args| # simulated signature: |b, c=1|Now the block behaves like if it had the signature |b, c=1|.
b, c = args[0], args[1] || 1
# validate number of arguments:
err = "wrong number of arguments"
if args.size > 2
raise ArgumentError, "#{err} (#{args.size} for 2)"
elsif args.size == 0
raise ArgumentError, "#{err} (0 for 1)"
end
end
1 comment:
does this change in Ruby 1.9?
Post a Comment