How do methods use hash arguments in Ruby?

前端 未结 6 1083
青春惊慌失措
青春惊慌失措 2020-12-04 19:43

I saw hash arguments used in some library methods as I\'ve been learning.

E.g.,

list.search(:titles, genre: \'jazz\', duration_less_than: 270)
         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 20:18

    When a Ruby method call's argument list ends in one or more key-value pairs, like foo: 'bar' or 'foo' => 1, Ruby collects them all into a single hash and passes that hash as the last parameter. You can see that yourself in irb:

    irb(main):002:0> puts foo: 'bar', baz: 'quux'
    {:foo=>"bar", :baz=>"quux"}
    => nil
    

    Thus, you can add a final, optional parameter to a method you're writing to receive this hash. You'll usually want to default it to an empty hash. You can call the parameter anything you want, but options is a common name:

    def my_method(a, b, c, options = {})
      ...
    end
    

    One useful trick if you're using Rails: It's often handy to treat plain strings and symbols as equivalent. Rails adds a symbolize_keys! method to Hash to convert all string keys to symbols:

    def my_method(a, b, c, options = {})
      options.symbolize_keys!
      ...
    end
    

提交回复
热议问题