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

后端 未结 5 945
轻奢々
轻奢々 2021-02-04 16:32

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
         


        
5条回答
  •  野性不改
    2021-02-04 17:04

    It's usually best to encapsulate safe defaults in a Hash that's declared as a constant. For example:

    require 'ostruct'

    require 'ostruct'
    
    class Tiger < OpenStruct
      DEFAULTS = {
        :num_stripes => 12,
        :max_speed => 43.2
      }.freeze
    
      def initialize(options = { })
        super(DEFAULTS.merge(options))
      end
    end
    
    tiger = Tiger.new(:max_speed => 19.95)
    
    puts tiger.max_speed
    puts tiger.num_stripes
    

    It is important to note when merging Hash objects that String and Symbol keys are different and will not be combined as you might expect. In the Rails environment, you can always convert one to the other using Hash#symbolize_keys or by declaring them as HashWithIndifferentAccess which maps away the difference for you.

提交回复
热议问题