Search code examples
ruby

How declaration of nested arrays interpreted in Ruby?


While i was working on arrays, I missed a comma in declaration of the nested array in Ruby but language interpreting this in other way. If anyone familiar about this behaviour please give a thought.

arr = [1,2[1,8]]
[1, 1] 
arr = [1,5[6,4]]
[1, 0] 
arr = [1,3[1,6]]
[1, 1] 
arr = [1,6[1,6]]
[1, 3] 
arr = [1,7[1,6]]
[1, 3] 
arr = [1,0[1,6]]
[1, 0] 
arr = [1,8[1,6]]
[1, 4]

An exception should be raised based on False Declaration


Solution

  • An exception should be raised [...]

    [1,8[1,6]] might look like a syntax error in the context of an array literal but it's actually a perfectly valid Ruby expression. It creates an array with two elements: 1 and the result from 8[1,6] which is 4.

    8[1,6] extracts a part of the integer 8. It does this by treating 8 as a sequence of bits (the binary number 00001000₂). From these bits, 6 bits are extracted, starting at bit 1: (with bit 0 being the right-most bit)

    0b00001000[1,6]  #=> 8
       ↓↓↓↓↓↓
     0b000100        #=> 4
    

    See the docs for Integer#[] for details.

    This is very similar to "hello ruby"[1,6] which extracts a part of the string by treating it as a sequence of characters: (with character 0 being the left-most character)

    "hello ruby"[1,6]
      ↓↓↓↓↓↓
     "ello r"