Float index on arrays

770 views

What's the return value of the following Ruby code?

a = [21, 42, 84]

a[1.2] # => ???

The correct answer is

It raise ArgumentError

[42, 84]

42

nil

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

This Ruby code creates an array a containing three elements: 21, 42, and 84.

Then, it accesses the element at index 1.2 of the array a.

Normally, in most programming languages, array indices are integers, so accessing an array element with a floating-point number might seem unusual.

However, in Ruby, this is allowed...

When using a floating-point number as an index to access an array, Ruby will truncate the decimal part of the number and treat it as an integer index.

In this case, a[1.2] evaluates to a[1], because 1.2 truncated to an integer becomes 1.

Therefore, the code a[1.2] returns the element at index 1 of the array a, which is 42.

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©