Unique construct for passing a hash

前端 未结 2 430
青春惊慌失措
青春惊慌失措 2021-01-27 03:58

I have never seen this construct for building a hash. do_stuff(records: records) Does this only work in a parameter list being sent to a method? Is it documented an

相关标签:
2条回答
  • 2021-01-27 04:13

    The new syntax for Hashes in Ruby 1.9 allows you to drop the hash rocket.

    #Pre 1.9
    {:key => value}
    
    #1.9+
    {key: value}
    

    Both of the above are equivalent.

    One thing to keep in mind when using the new hash syntax is that the key will always be treated as a symbol.

    0 讨论(0)
  • 2021-01-27 04:29

    There are two things going on here. The { key: value } syntax is new in Ruby 1.9. It is equivalent to { :key => value }.

    Also, Ruby methods have some syntactical sugar that allows you to pass in a hash literal as the last argument of the method without including the curly braces. This is not new in Ruby 1.9. So

    do_stuff(key: value)
    

    Is equivalent to

    do_stuff({ key: value })
    

    Just to remind you, this only works if the hash is the last argument to the method.

    0 讨论(0)
提交回复
热议问题