How to implement options hashes in Ruby?

后端 未结 4 1287
离开以前
离开以前 2021-02-06 14:47

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 whe

4条回答
  •  时光取名叫无心
    2021-02-06 15:31

    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
    

提交回复
热议问题