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

后端 未结 5 1081
轻奢々
轻奢々 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

    If you're using Rails (not just plain Ruby), a slightly shorter method is

    def foo(options = {})
      options.reverse_merge! { ... defaults ... }
    end
    

    This has the added advantage of allowing you to do multiple lines a tad bit more cleanly:

    def foo(options = {})
      options.reverse_merge!(
        :some_default => true,
        :other_default => 5
      )
    end
    

提交回复
热议问题