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

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

    In case anyone is seeing this from google, this question is old and out of date. The modern and much cleaner answer (with Ruby > 2.0) is to use keyword arguments. They have several advantages.

    1.) you can require the name of the key in the hash. (in ruby > 2.1)

    2.) you don't have to "unpack" the hash in the function. The keys are simply handed to you as variables. (thus you don't have to do like speed = opts[:speed])

    3.) It's cleaner

    def foo(num_stripes: 12, **rest)
      print num_stripes, rest
    end
    
    foo({max_speed: 42}) # would print '12, {max_speed: 42}'
    

    see full ruby docs here: http://www.ruby-doc.org/core-2.1.0/doc/syntax/methods_rdoc.html#label-Array%2FHash+Argument

    and a good little blog post here: http://robots.thoughtbot.com/ruby-2-keyword-arguments

提交回复
热议问题