What do the different brackets in Ruby mean?

前端 未结 6 2068
萌比男神i
萌比男神i 2020-12-04 16:40

In Ruby, what\'s the difference between {} and []?

{} seems to be used for both code blocks and hashes.

Are []

6条回答
  •  半阙折子戏
    2020-12-04 16:52

    a few examples:

    [1, 2, 3].class
    # => Array
    
    [1, 2, 3][1]
    # => 2
    
    { 1 => 2, 3 => 4 }.class
    # => Hash
    
    { 1 => 2, 3 => 4 }[3]
    # => 4
    
    { 1 + 2 }.class
    # SyntaxError: compile error, odd number list for Hash
    
    lambda { 1 + 2 }.class
    # => Proc
    
    lambda { 1 + 2 }.call
    # => 3
    

提交回复
热议问题