How do methods use hash arguments in Ruby?

前端 未结 6 1084
青春惊慌失措
青春惊慌失措 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:02

    Since Ruby 2.0 you can use keyword arguments [1][2] as opposed to the single Hash parameter.

    def foo(keyword_arg: 'bar')
      keyword_arg
    end
    

    And here's how it behaves.

    > foo
    => "bar"
    > foo(keyword_arg: 'baz')
    => "baz"
    
    1. http://robots.thoughtbot.com/ruby-2-keyword-arguments
    2. http://brainspec.com/blog/2012/10/08/keyword-arguments-ruby-2-0/

提交回复
热议问题