Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a nice clean way to use an options hash with defaults values as a parameter in ruby

Tags:

ruby

hash

Let's say I want a method which will be called like this:

 tiger = create_tiger( :num_stripes => 12, :max_speed => 43.2 )
 tiger.num_stripes # will be 12

where some of the options have default values:

 tiger = create_tiger( :max_speed => 43.2 )
 tiger.num_stripes # will have some default value

what's a nice idiomatic ruby way of implementing that defaulting behaviour in the method implementation?

like image 315
Pete Hodgson Avatar asked Jun 10 '09 19:06

Pete Hodgson


People also ask

How do you pass a default argument in Ruby?

Adding Default Arguments Default arguments are easy to add, you simply assign them a default value with = ("equals") in the argument list. There's no limit to the number of arguments that you can make default. Let's take a look at the different ways we can call this method: greeting # > Hello, Ruby programmer.

How do you call a hash value in Ruby?

Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.

What hash function does Ruby use?

The hashing functions included in Ruby's digest include: MD5, RIPEMED-160, SHA1, and SHA2. Each hashing function will accept an input variable, and the output can be returned in either a digest, hexidecimal, or “bubble babble” format.

What does .keys do in Ruby?

In Ruby, the key() method of a hash returns the key for the first-found entry with the given value. The given value is passed as an argument to this method.


2 Answers

def foo(options = {})
  options = { ... defaults ... }.merge(options)
end
like image 63
Steve Madsen Avatar answered Sep 18 '22 17:09

Steve Madsen


If you're using Rails (not just plain Ruby), a slightly shorter method is

def foo(options = {})
  options.reverse_merge! { ... defaults ... }
end

This has the added advantage of allowing you to do multiple lines a tad bit more cleanly:

def foo(options = {})
  options.reverse_merge!(
    :some_default => true,
    :other_default => 5
  )
end
like image 27
Topher Fangio Avatar answered Sep 21 '22 17:09

Topher Fangio