在Ruby中,{}[]有什么区别?

{}似乎用于代码块和哈希.

[]只适用于数组吗?

文件不是很清楚.

推荐答案

这取决于上下文:

  1. 当它们自己或分配给变量时,[]创建数组,{}创建散列.例如

    a = [1,2,3] # an array
    b = {1 => 2} # a hash
    
  2. []可以作为自定义方法重写,通常用于从散列中获取内容(标准库将[]设置为与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.

  3. 这可能是最棘手的一个-

    当您在没有参数的情况下调用方法时,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
    

Ruby相关问答推荐

为什么 rdoc 注释似乎以两个井号/井号符号开头?

如何判断 postgres 中使用 ruby​​ 的查询是否失败?

Faraday中的timeout和open timeout是什么?

有没有办法通过哈希初始化对象?

为什么 Range 在下降时不起作用?

如何从正在运行的脚本进入 IRB 提示符?

我如何 expect期望在 RSpec 中引发异常的东西?

在文件中搜索字符串的最佳方法是什么?

如何将消息附加到 RSpec 判断?

按可能为 nil 的属性对对象的 ruby​​ 数组进行排序

Vagrant - 如何拥有特定于主机平台的配置步骤

Ruby 哈希默认值行为

为什么 Ruby 无法验证 SSL 证书?

测试变量是否等于两个值之一

如何理解 strptime 与 strftime

Ruby总是Round Up

从数组 Ruby 中删除元素

正则表达式中的 `?i` 和 `?-i` 是什么意思?

Rubocop 25 线块大小和 RSpec 测试

查找模块中可用的类