Ruby 中的不同括号是什么意思? [英] What do the different brackets in Ruby mean?

查看:48
本文介绍了Ruby 中的不同括号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

[] 仅用于数组吗?

文档不是很清楚.

推荐答案

这取决于上下文:

  1. 当单独使用或分配给变量时,[] 创建数组,{} 创建哈希.例如

  1. When on their own, or assigning to a variable, [] creates arrays, and {} creates hashes. e.g.

a = [1,2,3] # an array
b = {1 => 2} # a hash

  • [] 可以作为自定义方法进行覆盖,一般用于从哈希中获取东西(标准库将 [] 设置为方法在与 fetch 相同的哈希上)
    还有一个约定是将它用作类方法,就像在 C# 或 Java 中使用 static Create 方法一样.例如

  • [] can be overridden as a custom method, and is generally used to fetch things from hashes (the standard library sets up [] as a method on hashes which is the same as fetch)
    There is also a convention that it is used as a class method in the same way you might use a static Create method in C# or Java. e.g.

    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 哈希文档 最后一个例子.

    See the Ruby Hash docs for that last example.

    这可能是最棘手的一个——{} 也是块的语法,但仅当传递给参数括号之外的方法时.

    This is probably the most tricky one - {} is also syntax for blocks, but only when passed to a method OUTSIDE the arguments parens.

    当您调用不带括号的方法时,Ruby 会查看您放置逗号的位置,以确定参数的结束位置(如果您键入它们,括号会在哪里)

    When you invoke methods without parens, Ruby looks at where you put the commas to figure out where the arguments end (where the parens would have been, had you typed them)

    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 中的不同括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆