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

后端 未结 5 947
轻奢々
轻奢々 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 16:45

    Rails 6 (don't know what version is this available from) has a semantic alias:

    def a_method(options={})
      options.with_defaults!(
        a_key: :a_default_value,
        b_key: :b_default_value,
        ..
      )
      ..
    end
    

提交回复
热议问题