簡體   English   中英

Ruby中不同的括號是什么意思?

[英]What do the different brackets in Ruby mean?

在Ruby中, {}[]之間有什么區別?

{}似乎用於代碼塊和哈希。

[]僅用於數組嗎?

文件不是很清楚。

這取決於具體情況:

  1. 當它們獨立或分配給變量時, []創建數組,而{}創建哈希。 例如

     a = [1,2,3] # an array b = {1 => 2} # a hash 
  2. []可以作為自定義方法重寫,通常用於從哈希中獲取內容(標准庫設置[]作為哈希方法,與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文檔

  3. 這可能是最棘手的一個 - {}也是塊的語法,但只有在傳遞給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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM