Are there “rules” for Ruby syntactic sugar?

前端 未结 4 885
-上瘾入骨i
-上瘾入骨i 2021-02-10 06:22

I\'m learning the basics of Ruby (just starting out), and I came across the Hash.[] method. It was introduced with

a = [\"foo\", 1, \"bar\", 2]
=> [\"foo\", 1         


        
4条回答
  •  灰色年华
    2021-02-10 07:21

    The * method tells ruby not to take the array as array, but to use the 'expanded' array.

    Example:

    def test(*argv)
      p argv
    end
    
    a = [1,2,3]
    test(a) #-> [[1, 2, 3]]
    test(*a) #-> [1, 2, 3]    
    

    With test(a) the array a is the one and only parameter.

    With test(*a) a is used as a list of parameters.


    In your case

    a = ["foo", 1, "bar", 2]
    Hash[*a]
    

    is similar to

    Hash["foo", 1, "bar", 2]
    

    Hash[*a] would be

    Hash[["foo", 1, "bar", 2]]
    

提交回复
热议问题