Search code examples
arraysrubyrandommaxlength

Why "array.length" returns array object when we put it inside array[]?


rand(array.length)        # returns random index <br>
array[rand(array.length)] # returns random array object

I can't understand the logic behind. I would assume that second example also returns random index and then store it in array.

kitty = [100,102,104,105]

rand(kitty.length)        # returns index, for example 3 ( or 0,1,2 )
array[rand(kitty.length)] # returns random array object, for example 104 ( or 100,102,105)

Solution

  • While array.sample would be the best way to get a random element from an array, I believe OP is asking how the chaining of methods works.

    When you call: rand(array.length) a number is returned, true. However in the case of:

    array[ rand(array.length) ]
    

    a number is returned but then fed immediately into the array call, which gives you the object at that array index.