Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement options hashes in Ruby?

Tags:

ruby

How can I implement options hashes? How is the structure of a class that has option hashes in it? Say I have a person class. I want to implement a method such as my_age that when called upon will tell me my age using options hashes.

like image 832
Andy Huynh Avatar asked Dec 26 '22 09:12

Andy Huynh


2 Answers

You could 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're able to call to the age like this

p1 = Person.new(:age => 24)<br/>
p2 = Person.new

p1.my_age # => 24<br/>
p2.my_age # => nil
like image 195
JtoTheGoGo Avatar answered Jan 08 '23 08:01

JtoTheGoGo


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
like image 21
Mori Avatar answered Jan 08 '23 08:01

Mori