Weird ruby code: Float Index and character literal

Disclaimer: This code is purely for educational purposes! You might encounter similar scenarios in the future, but do not push similar code to production.

Always ensure your indexing is intentional and clear!

a = [*?a..?z] # => ['a', 'b', 'c', ..., 'z']
a[3.1415926]  # => "d"

Range Expansion with the Splat Operator (*)

The expression [*?a..?z] creates an array of all lowercase letters from 'a' to 'z'.

?a is the character literal for the letter 'a', and ?z is the character literal for 'z'.

The .. is the range operator, and the [*...] expands the range into an array.

So, [*?a..?z] is equivalent to writing ['a', 'b', 'c', ..., 'z'].

Accessing an Array with a Float Index

a[3.1415926] attempts to access an element from the array a using the float 3.1415926 as an index.

Ruby handles this by converting the float index to an integer using Float#to_i, which truncates the decimal part without rounding. Therefore, 3.1415926.to_i becomes 3.

Accessing the Element at Index 3

The element at index 3 of the array a is 'd' (since Ruby arrays are zero-indexed: index 0 is 'a', index 1 is 'b', index 2 is 'c', and index 3 is 'd'). So, the code returns "d".

RubyCademy

This is fun to explore, but it's not something you'll come across in your day-to-day work.

For core concepts, lesser-known techniques, and powerful patterns, check out RubyCademy.

Voilà!

RubyCademy ©