题
在 Ruby 中,有什么区别 {}
和 []
?
{}
似乎既用于代码块又用于哈希值。
是 []
仅适用于数组?
文档不是很清楚。
解决方案
这取决于上下文:
当单独使用或分配给变量时,
[]
创建数组,并且{}
创建哈希值。例如a = [1,2,3] # an array b = {1 => 2} # a hash
[]
可以作为自定义方法重写,通常用于从哈希中获取内容(标准库设置[]
作为哈希上的方法,与以下相同fetch
)
还有一个约定,它用作类方法,就像使用static Create
C# 或 Java 中的方法。例如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 会查看您放置逗号的位置来找出参数结束的位置(如果您键入了括号,它们本来应该在哪里)
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
其他提示
另一种不太明显的用法是 []
是 Proc#call 和 Method#call 的同义词。当您第一次遇到它时,这可能会有点令人困惑。我猜其背后的原因是它使它看起来更像是一个正常的函数调用。
例如。
proc = Proc.new { |what| puts "Hello, #{what}!" }
meth = method(:print)
proc["World"]
meth["Hello",","," ", "World!", "\n"]
从广义上讲,你是对的。除了散列之外,一般样式是花括号 {}
通常用于可以将所有内容放入一行的块,而不是使用 do
/end
跨越几条线。
方括号 []
在许多 Ruby 类中用作类方法,包括 String、BigNum、Dir 以及令人困惑的 Hash。所以:
Hash["key" => "value"]
与以下内容一样有效:
{ "key" => "value" }
方括号[]用于初始化数组。[ ] 的初始值设定项情况的文档位于
ri Array::[]
大括号 { } 用于初始化哈希值。{ } 的初始值设定项情况的文档位于
ri Hash::[]
方括号也常被用作许多核心 ruby 类中的方法,例如 Array、Hash、String 等。
您可以访问具有定义方法“[ ]”的所有类的列表
ri []
大多数方法还有一个“[ ]=”方法,允许分配事物,例如:
s = "hello world"
s[2] # => 108 is ascii for e
s[2]=109 # 109 is ascii for m
s # => "hemlo world"
也可以使用大括号代替“do ...end”在块上,如“{ ...}”。
您可以看到使用方括号或大括号的另一种情况 - 是在可以使用任何符号的特殊初始值设定项中,例如:
%w{ hello world } # => ["hello","world"]
%w[ hello world ] # => ["hello","world"]
%r{ hello world } # => / hello world /
%r[ hello world ] # => / hello world /
%q{ hello world } # => "hello world"
%q[ hello world ] # => "hello world"
%q| hello world | # => "hello world"
举几个例子:
[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
请注意,您可以定义 []
你自己的类的方法:
class A
def [](position)
# do something
end
def @rank.[]= key, val
# define the instance[a] = b method
end
end