Conditional parameters in Ruby
Posted by Daniel Brahneborg on 2007 March 12
All cool Ruby hackers probably use this all the time, but I think it’s worth mentioning anyway.
I have a generic send_operation()
function that takes a hash table of parameters to send. It’s used as the backend for the more user friendly things like login() etc. Some of the functions take a single, optional parameter. First I used the simple version:
args = nil
(args ||= {})[key] = value unless value.nil?
result = send_operation(op, args)
However, it can be made much nicer, using the fact that everything has a value. Combined with the “unless
” modifier, I got a single line version that looks like this:
result = send_operation(op, ({ key=> value } unless value.nil?))
The parentheses around the “unless
” construct is necessary, or Ruby gets a bit upset. Since there is an extensive unit test suite for all functions in all versions, it was easy to verify that it works correctly.
Andra bloggar intressant om programmering, ruby.
Leave a comment