How to implement option hashes in Ruby?

How can I implement option hashes? What is the structure of a class that has hash options? Say I have a human class. I want to implement a method like my_age, which when called will tell me my age using option hashes.

+4
source share
4 answers

You can do something like this:

class Person def initialize(opts = {}) @options = opts end def my_age return @options[:age] if @options.has_key?(:age) end end 

and now you can call at that age

 p1 = Person.new(:age => 24)<br/> p2 = Person.new p1.my_age # => 24<br/> p2.my_age # => nil 
+6
source
 class Person def birth_date Time.parse('1776-07-04') end def my_age(opts=nil) opts = { as_of_date: Time.now, birth_date: birth_date, unit: :year }.merge(opts || {}) (opts[:as_of_date] - opts[:birth_date]) / 1.send(opts[:unit]) end end 
+3
source

It might be worth mentioning that Ruby 2.1 adds the ability to pass keyword arguments that shouldn't be in a specific order, and you can make them mandatory or have default values.

Dropping the parameter hash reduces the pattern code to retrieve the hash options. Unnecessary boilerplate code increases the possibility of typos and errors.

Also with the keyword arguments defined in the method signature itself, you can immediately find the argument names without reading the body of the method.

Mandatory arguments are followed by a colon, while arguments with default values ​​are passed in the signature, as you would expect.

For instance:

 class Person attr_accessor(:first_name, :last_name, :date_of_birth) def initialize(first_name:, last_name:, date_of_birth: Time.now) self.first_name = first_name self.last_name = last_name self.date_of_birth = date_of_birth end def my_age(as_of_date: Time.now, unit: :year) (as_of_date - date_of_birth) / 1.send(unit) end end 
+1
source

In Ruby 2.x, you can use the ** operator:

 class Some def initialize(**options) @options = options end def it_is? return @options[:body] if @options.has_key?(:body) end end 
0
source

All Articles