This are my notes in the fields of computer science and technology. Everything is written with ABSOLUTE NO WARRANTY of fitness for any purpose. Of course, feel free to comment anything.

Monday, August 18, 2008

Default values in Ruby blocks

The ruby parser does not allow default values to be set in blocks, unlike in method signatures. This is of course valid ruby:
def method(a, b=0)
#...
end
but this isn't:
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|
b, c = args[0], args[1] || 1
end
This has the disadvantage that is not validating the number of arguments, so let's add some validation code to the block:
lambda do |*args| # simulated 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
Now the block behaves like if it had the signature |b, c=1|.

About Me

My photo
Hamburg, Hamburg, Germany
Former molecular biologist and web developer (Rails) and currently research scientist in bioinformatics.