Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Ruby's array work?

Tags:

arrays

ruby

When I input

p [[2,1],3,4][1][1]

It will output 1.

Why is that happening?

like image 280
Shukai Ni Avatar asked Dec 08 '22 21:12

Shukai Ni


1 Answers

  • [2,1] creates an array with two elements (2, 1)
  • [[2,1],3,4] creates an array with three elements ([2,1], 3 and 4)
  • [1] indexes that array and returns the second element 3 (indexing is 0 based)
  • [1] indexes the second bit of the number 3 (represented in binary as 11) - aka 1
like image 95
ndnenkov Avatar answered Dec 24 '22 14:12

ndnenkov