質問
にRubyの違いについて教えてください {}
や []
?
{}
のように使用するもコードブロックとハッシュ.
は []
のみ、アレイ?
のdocumentionなクリアになっています。
解決
によってはコンテクスト:
場合、または提供す変数
[]
を作成し配列、{}
をハッシュ.例えばa = [1,2,3] # an array b = {1 => 2} # a hash
[]
オーバーライドできとして、カスタム方法は、一般的に用いられてい取得したものからハッシュ(標準ライブラリを設定[]
方法としては、上のハッシュがとても充実していますし、fetch
)
もあり、条約として使用されるクラスのメソッドを同じように利用する場合もあるでしょうstatic Create
方法クライアントまで、フルのC#または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 ハッシュdocs その最後の例です。
これは、おそらく最もトリッキーにつ
{}
も構文のためのブロックのみが渡される方法以外の引数のパー.ときに呼び出し方法なパー、ルビーを見するのは次のとおりですが、引数末のパーされていったん入力し)
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
他のヒント
別のない明らかな利用の []
は詩として集#電話ソフト。これまでのプログラムが混乱を最初に出会います。しないといけないのではないかの合理的な背景でそうとうに正常に機能する。
E.g.
proc = Proc.new { |what| puts "Hello, #{what}!" }
meth = method(:print)
proc["World"]
meth["Hello",","," ", "World!", "\n"]
大きく分けています。どのハッシュは、一般的なスタイルで巻きブレース {}
使用することが多くのブロックで全てを一つの回線を使わずに do
/end
全複数の行に展開されています。
角括弧 []
を使用していクラスメソッドのRubyクラスを含む文字列、BigNum、Dirは、紛らわしい外観もハッシュ.い:
Hash["key" => "value"]
あんなこと言わなければ有効として
{ "key" => "value" }
は、角括弧[]は初期化に使用される配列.ドキュメンテーションに初期化の場合は[]で
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"
巻きブラケットで使用することもりくださ---end"のブロックには、"{...}".
別の場合をご覧の角括弧または巻きブラケット使用は、特別initializersがシンボル使用できるように:
%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