How to implement options hashes in Ruby?

后端 未结 4 1359
离开以前
离开以前 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:26

    Might be worth mentioning that Ruby 2.1 adds the ability to pass in keyword arguments that don't need to be in a particular order AND you can make them be required or have default values.

    Ditching the options hash reduces the boilerplate code to extract hash options. Unnecessary boilerplate code increases the opportunity for typos and bugs.

    Also with keyword arguments defined in the method signature itself, you can immediately discover the names of the arguments without having to read the body of the method.

    Required arguments are followed by a colon while args with defaults are passed in the signature as you'd expect.

    For example:

    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
    

提交回复
热议问题