Rubyでは、違いは何だ{}とは[]?
{} コードブロックとハッシュの両方に使用されているようです。
ある[]配列のみのために?
文書化はあまり明確ではありません。
回答:
それは文脈に依存します:
単独で、または変数に割り当てると、[]配列が{}作成され、ハッシュが作成されます。例えば
a = [1,2,3] # an array
b = {1 => 2} # a hash
[]カスタムメソッドとしてオーバーライドでき、通常はハッシュから物をフェッチするために使用されます(標準ライブラリは[]ハッシュのメソッドとして設定されます。これはと同じですfetch)。同じ
クラスメソッドとして使用されるという規則もあります。static CreateC#または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ハッシュのドキュメントを参照してください。
これはおそらく最もトリッキーなものです-
{}ブロックの構文でもありますが、引数の範囲外のメソッドに渡された場合のみです。
パレンなしでメソッドを呼び出すと、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
:cが見つかりません
角括弧[]は、配列を初期化するために使用されます。[]の初期化子の場合のドキュメントは
ri Array::[]
中括弧{}は、ハッシュを初期化するために使用されます。{}の初期化子の場合のドキュメントは
ri Hash::[]
角括弧は、Array、Hash、Stringなどの多くのコアrubyクラスのメソッドとしても一般的に使用されます。
メソッド「[]」が定義されているすべてのクラスのリストにアクセスできます。
ri []
ほとんどのメソッドには、次のようなものを割り当てることができる "[] ="メソッドもあります。
s = "hello world"
s[2] # => 108 is ascii for e
s[2]=109 # 109 is ascii for m
s # => "hemlo world"
ブロックの「do ... end」の代わりに、「{...}」のように中括弧を使用することもできます。
角括弧または中括弧が使用されていることを確認できるもう1つのケースは、次のような任意の記号を使用できる特別な初期化子です。
%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
@rank.ですか?