[英]What do the different brackets in Ruby mean?
在Ruby中, {}
和[]
之间有什么区别?
{}
似乎用于代码块和哈希。
[]
仅用于数组吗?
文件不是很清楚。
这取决于具体情况:
当它们独立或分配给变量时, []
创建数组,而{}
创建哈希。 例如
a = [1,2,3] # an array b = {1 => 2} # a hash
[]
可以作为自定义方法重写,通常用于从哈希中获取内容(标准库设置[]
作为哈希方法,与fetch
相同)
还有一种约定,它可以像在C#或Java中使用static Create
方法一样用作类方法。 例如
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文档 。
这可能是最棘手的一个 - {}
也是块的语法,但只有在传递给OUTSIDE方法的参数parens时。
当您调用没有parens的方法时,Ruby会查看您放置逗号的位置以确定参数的结束位置(如果您输入了parens,那么它们会在哪里出现)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.