What do the different brackets mean in Ruby?

In Ruby, what's the difference between {} and [] ?

{} seems to be used for both code blocks and hashes.

Are [] only for arrays?

The documentation is not very clear.

+72
syntax ruby
Aug 15 '08 at 18:09
source share
6 answers

It depends on the context:

  • When they themselves or assign a variable, [] creates arrays, and {} creates hashes. eg.

     a = [1,2,3] # an array b = {1 => 2} # a hash 
  • [] can be redefined as a user method and is usually used to extract data from hashes (the standard library sets [] as a hash method that matches fetch ) <w> There is also an agreement that it is used as a class method in the same way you can use the static Create method in C # or Java. eg.

     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 

    Refer to the Ruby Hash docs for this final example.

  • This is probably the trickiest - {} also the syntax for blocks, but only when passing parens arguments to the OUTSIDE method.

    When you call methods without partners, Ruby looks at where you put the commas to find out where the arguments end (where would parens be if you typed them)

     1.upto(2) { puts 'hello' } # it 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 
+63
Aug 17 '08 at 21:17
source share

Another, not so obvious, use of [] is synonymous with calling Pro # and calling a method #. This may be a little confusing the first time you come across this. I believe that a reasonable approach is that it looks more like a regular function call.

eg.

 proc = Proc.new { |what| puts "Hello, #{what}!" } meth = method(:print) proc["World"] meth["Hello",","," ", "World!", "\n"] 
+18
Apr 02 '09 at 15:47
source share

In general, you are right. Like hashes, the general style is that curly braces {} are often used for blocks that can put everything on one line, instead of using do / end for several lines.

Square brackets [] are used as class methods in a variety of Ruby classes, including String, BigNum, Dir and, rather vaguely, Hash. So:

 Hash["key" => "value"] 

fair as:

 { "key" => "value" } 
+9
Aug 15 '08 at 18:24
source share

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" 
+3
Sep 17 '08 at 7:52
source share

a few examples:

 [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 
+2
Aug 15 '08 at 19:03
source share

Note that you can define the [] method for your own classes:

 class A def [](position) # do something end def @rank.[]= key, val # define the instance[a] = b method end end 
+2
Oct 13 '09 at 21:47
source share



All Articles