简体   繁体   English

Ruby 中 [方括号] 的所有不同用途是什么?

[英]What are all the different uses of the [square brackets] in Ruby?

I'm coming across the square bracket [] syntax quite a bit in Ruby, but it never seems to be doing the same thing.我在 Ruby 中经常遇到方括号[]语法,但它似乎从来没有做同样的事情。 Can anyone list all the different uses for the square brackets [] in Ruby so my mind can get a handle on this seemingly endlessly versatile little symbol?任何人可以列出 Ruby 中方括号[]所有不同用途,以便我的头脑可以处理这个看似无穷无尽的小符号吗? (How is it possible that one symbol can do so much without the Ruby interpreter getting confused?) (一个符号怎么可能做这么多事情而不会让 Ruby 解释器感到困惑?)

Examples:例子:

  • [] and []= methods [][]=方法
  • %q[...]
  • [1,2,3][0]
  • hash["a"] = 3
  • ary = []
  • /[^A-Fa-f0-9]/
  • "Is a string"[5,3]

The square brackets are in two strict contexts and one optional one: 方括号分为两个严格的上下文和一个可选的上下文:

Defining Arrays 定义数组
Arrays, ie a data structure providing and ordered list of elements can be specified in code by using a syntax like [1,2,3] . 可以使用类似[1,2,3]的语法在代码中指定数组,即提供元素和有序元素列表的数据结构。 This creates an array with the three elements 1 , 2 , and 3 in exactly that order. 这产生与所述三个元素的数组12 ,和3中完全相同的顺序。 you can then iterate over the array using on of the iterator functions like each or map or you can directly access a specific elements by its index id as shown below. 然后,您可以使用迭代器函数(如eachmap迭代数组,或者您可以通过其索引ID直接访问特定元素,如下所示。

Accessing Elements in Arrays and Hashes 访问数组和散列中的元素
Hashes (also called hashmaps, dictionaries, or associative arrays in other languages) also contain elements similar to arrays. 哈希(在其他语言中也称为哈希映射,字典或关联数组)也包含与数组类似的元素。 The are different from this in the way that they store their data unordered . 与它们存储数据无序的方式不同。 Data is not accessed by an integer id as is the case by arrays but with an arbitrary key (commonly a symbol or a string). 数据不是由整数id访问的,就像数组一样,但是具有任意键(通常是符号或字符串)。 This is different from eg PHP where the same Array type is used for both. 这与例如PHP不同,其中两者使用相同的Array类型。

This access to the data is facilitated by methods called [] and []= for both hashes and arrays. 对于哈希和数组,通过调用[][]=的方法可以方便地访问数据。

my_array = [:a, :b, :c]
second_element = my_array[1]
# => :b
# notice that the first element in arrays always has the index 0

my_hash = {:a => 1, :b => 2, :c => 3}
element_of_b = my_hash[:b]
# => 2

This is the common use case for the brackets. 这是括号的常见用例。 In Ruby code, you might sometimes see other classes implementing the bracket functions. 在Ruby代码中,您有时可能会看到其他类实现括号函数。 They do so to allow an access similar to either arrays or hashes and it is then generally expected that these classes behave similar to those but this is in no way enforced. 他们这样做是为了允许类似于数组或哈希的访问,然后通常期望这些类的行为与那些类似,但这绝不是强制执行的。 See also Duck Typing . 另见鸭子打字

% Notation %表示法
Ruby has a third syntax to create strings (and other objects) apart from the common. Ruby有第三种语法来创建除常见之外的字符串(和其他对象)。 Using this syntax, the literal string in code are not enclosed by " or ' but use a special delimiter. It starts with a percent sign, a single character specifying the object to be created and almost any character to chose as a delimiter: 使用这种语法,代码中的文字字符串不包含在"'而是使用特殊的分隔符。它以百分号开头,单个字符指定要创建的对象,几乎任何字符都选择作为分隔符:

a = %w[foo bar baz]
b = %w{foo bar baz}
c = %wxfoo bar bazx
d = ["foo", "bar", "baz"]

All three example create the same array. 这三个示例都创建了相同的数组。 Please see the some documentation on how to use this syntax and which other modifier characters are available in Ruby. 请参阅一些有关如何使用此语法的文档以及Ruby中可用的其他修饰符。

While it is common to use brackets here, it is on no way required and can be substituted if required. 虽然这里通常使用括号,但它绝不是必需的,如果需要可以替换。 It is just advisory here as the most common usage of this notation is to create an array of elements from a whitespace-seperated string (as seen above). 这里只是建议,因为这种表示法的最常见用法是从空格分隔的字符串创建一个元素数组(如上所示)。 As such, the usage of brackets makes it further clear that an array is returned as the syntax looks similar to the basic array specification. 因此,括号的使用使得进一步清楚返回数组,因为语法看起来类似于基本数组规范。

Okay, just for my own notes I have gone and had a closer look at this and, building on Holger Just's answer , come up with the following: the use of square brackets in Ruby can be divided into 6 uses, 3 of them a part of Ruby's method definitions and 3 of them semantic constructs. 好吧,只是为了我自己的笔记,我已经走了,仔细看看这个,并在Holger Just的答案的基础上 ,提出以下内容:在Ruby中使用方括号可以分为6个用途,其中3个是一部分Ruby的方法定义和其中3个语义结构。

Method definition 方法定义

Object creation via class methods Array::[], Hash::[] 通过类方法创建对象Array :: [],Hash :: []

Array.[](1,2,3) #=> [1,2,3]                        #Un-sugared notation
Array["a","b","c"] #=> ["a","b","c"]               #Sugared equivalent
Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}  

Nothing to do with literal constructors, although it does the same thing. 与文字构造函数无关,尽管它做同样的事情。

Element reference via instance methods Array#[], Bignum#[], Continuation#[], Fixnum#[], Hash#[], MatchData#[], Method#[], Proc#[], String#[], Struct#[], Symbol#[], Thread#[], and class methods Dir::[], ENV::[] 元素引用通过实例方法Array#[],Bignum#[],Continuation#[],Fixnum#[],Hash#[],MatchData#[],Method#[],Proc#[],String#[], Struct#[],Symbol#[],Thread#[]和类方法Dir :: [],ENV :: []

ary = [1,2,"abc", [15,16,[26,27]]]  
ary.[](2) #=> "abc"                #Un-sugared notation
ary[2] #=> "abc"                   #Sugared equivalent
ary[0,2] #=> [1,2]  
ary[3][2][1] #=> 26  
[1,2,3][0] #=> 1  
"Is a string"[7,3] #=> "rin"  

Element assignment via instance methods Array#[]=, Hash#[]=, String#[]=, Struct#[]=, Thread#[]=, and class method ENV::[]= 通过实例方法进行元素赋值Array#[] =,Hash#[] =,String#[] =,Struct#[] =,Thread#[] =,类方法ENV :: [] =

ary = [1,2,3]  
ary.[]=(1,"abc") #=> [1,"abc",3]    #un-sugared notation
ary[2] = "def" #=> [1,"abc","def"]  #Sugared equivalent
hash = {"a"=>1, "b"=>2}  
hash["a"] = 3 #=> {"a"=>3, "b"=>2}  

Semantic constructs 语义结构

Object creation via the array literal constructor 通过数组文字构造函数创建对象

ary = []  

There are a bunch of literal constructors in Ruby that create an object of the relevant class via the use of (usually) a simple symbol pair, square brackets being the literal constructor for array objects: Array [] , Hash {} , Proc ->(){} , Range .. and ... , Regexp // , String "" and '' , Symbol : and :"" . Ruby中有一堆文字构造函数通过使用(通常)一个简单的符号对来创建相关类的对象,方括号是数组对象的文字构造函数:Array [] ,Hash {} ,Proc ->(){} ,Range ..... ,Regexp // ,String ""'' ,符号::""

Object creation via the % notation 通过%表示法创建对象

%q[hello there you] #=> "hello there you"           # String % notation  
%w[hello there you] #=> ["hello", "there", "you"]   # Array % notation  

It is not, strictly speaking, square-bracket notation, but rather two-symbol-pair notation of which you can use square brackets if you wish. 严格来说,它不是方括号表示法,而是两符号对符号,如果您愿意,可以使用方括号。 So %q@hello there you@ is equally valid. 所以%q@hello there you@同样有效。

Ruby's regular expressions Ruby的正则表达式

/[^A-Fa-f0-9]/  

Square brackets indicate character classes in Ruby regular expressions. 方括号表示Ruby正则表达式中的字符类。

I did find another use of the [] , as a pattern for use in the Dir::glob method, but its supposed to act exactly as it does in regular expressions. 我确实发现[]另一个用途,作为在Dir :: glob方法中使用的模式,但它应该完全像在正则表达式中那样。 Still, it indicates that there are possibly more uses hidden away in Ruby's 1500+ methods. 不过,它表明Ruby的1500多种方法中可能存在更多用途。

handy syntax for instantiating structs with square brackets使用方括号实例化结构的方便语法

irb(main):001:0> Point = Struct.new(:x, :y)                         
=> Point                      
irb(main):002:0> point = Point[1,2]                                 
=> #<struct Point x=1, y=2>   
irb(main):003:0> point.x                   
=> 1                           
irb(main):004:0> point.y                    
=> 2     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM