Square brackets [] are used to initialize arrays. The documentation for the initialization case [] is located in
ri Array::[]
The curly braces {} are used to initialize hashes. The documentation for the initialization case {} is in
ri Hash::[]
Square brackets are also commonly used as a method in many major ruby ββclasses, such as Array, Hash, String, etc.
You can access the list of all classes that have the "[]" method defined with
ri []
most methods also have a "[] =" method that allows you to assign things, for example:
s = "hello world" s[2] # => 108 is ascii for e s[2]=109 # 109 is ascii for m s # => "hemlo world"
Tumble brackets can also be used instead of "do ... end" on blocks, like "{...}".
Another case where you can see square brackets or braces used is in special initializers, where any character can be used, for example:
%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"
Evgeny Sep 17 '08 at 7:52 2008-09-17 07:52
source share