Basic tech stuff

Programming and Linux administration

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 om , .


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: