这取决于上下文:
当它们自己或分配给变量时,[]
创建数组,{}
创建散列.例如
a = [1,2,3] # an array
b = {1 => 2} # a hash
[]
可以作为自定义方法重写,通常用于从散列中获取内容(标准库将[]
设置为与fetch
相同的散列方法)
a = {1 => 2} # create a hash for example
puts a[1] # same as a.fetch(1), will print 2
Hash[1,2,3,4] # this is a custom class method which creates a new hash
最后一个例子见Ruby Hash docs.
这可能是最棘手的一个-
当您在没有参数的情况下调用方法时,Ruby会查看在何处放置逗号,以确定参数的结束位置(如果您键入了参数,则参数会在何处)
1.upto(2) { puts 'hello' } # it's a block
1.upto 2 { puts 'hello' } # syntax error, ruby can't figure out where the function args end
1.upto 2, { puts 'hello' } # the comma means "argument", so ruby sees it as a hash - this won't work because puts 'hello' isn't a valid hash