2008-08-15 13 views

回答

63

這取決於上下文:

  1. 當自己,或者分配給一個變量,[]創建一個rray,並且{}創建散列。例如

    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 
    

    查看最後一個例子的紅寶石Hash docs

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

邊注:哈希#取不完全散列# []。 {:a => 1,:b => 2} .fetch(:c)IndexError:找不到密鑰 – tokland 2011-02-13 12:43:27

+0

@tokland`:c` not found – YoYoYonnY 2016-12-27 10:58:03

+0

「還有一個約定,它被用作類你也可以在C#或Java中使用靜態的Create方法。「這正是我正在尋找的答案。也是我最討厭Ruby的經典例子;你必須知道很多晦澀的小技巧來閱讀Ruby代碼。 – Tony 2017-08-28 14:37:15

9

從廣義上講,你是對的。除了散列之外,一般風格是大括號{}通常用於可以全部放在一行上的塊,而不是跨多行使用do/end

方括號[]被用作很多Ruby類的類方法,包括String,BigNum,Dir和足夠容易混淆的哈希。所以:

Hash["key" => "value"] 

只是爲有效爲:

{ "key" => "value" } 
2

幾個例子:

[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 
+0

拉姆達{1 + 2} []#=> 3 – 2011-09-01 02:37:36

3

的方括號[]用於初始化數組。 爲[]的初始化的情況下該文檔是在

ri Array::[] 

的大括號{}用來初始化哈希。 爲{初始化情況下}的文檔是

ri Hash::[] 

方括號也通常用作許多核心紅寶石類的方法,例如數組,散列,字符串,以及其他。

您可以訪問有方法「[]」與定義的所有類的列表

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" 
19

另外,不那麼明顯,[]用途是作爲Proc#調用和Method#調用的同義詞。這可能會讓你第一次遇到它有點困惑。我猜它背後的理由是它使它看起來更像一個正常的函數調用。

E.g.

proc = Proc.new { |what| puts "Hello, #{what}!" } 
meth = method(:print) 

proc["World"] 
meth["Hello",","," ", "World!", "\n"] 
2

請注意,可以定義自己的類的[]方法:

class A 
def [](position) 
    # do something 
end 

def @rank.[]= key, val 
    # define the instance[a] = b method 
end 

end 
相關問題