select(&:itself)

579 views

FREE SAMPLE OF THE PRO VERSION

What is the return value of the following Ruby code?

a = [1, 2, nil, 2, "", false, 3]

a.select(&:itself) # => ???

The correct answer is

[1, 2, 3]

[1, 2, 2, "", 3]

[1, 2, 2, 3]

[1, 2, nil, 2, "", false, 3]

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

The following Ruby idiom demonstrates the use of the select method along with the &:itself shorthand to filter out elements from an array that are not truthy.

Let's break down the code step by step:

a = [1, 2, nil, 2, "", false, 3]

In this line, an array a is defined with various elements, including integers, nil, an empty string, and a boolean value.

a.select(&:itself)

Here, the select method is used on the array a with &:itself as argument.

The &:itself Symbol-to-Proc is a shorthand notation in Ruby, often used to create a block that represents the identity function, essentially returning the element itself (self).

In this case, select(&:itself) is equivalent to select { |x| x.itself }, and it returns true for truthy values and false for falsy values.

The result of a.select(&:itself) is a new array containing only the elements for which the block evaluates to true.

In Ruby, only nil and false are considered falsy, so the resulting array includes elements that are truthy:

[1, 2, 2, "", 3]

The use of &:itself simplifies the block by representing the identity function, making the code concise and readable.

This idiom is particularly interesting as compact and compact_blank act diffently:

a = [1, 2, nil, 2, "", false, 3]

a.select(&:itself) # => [1, 2, 2, "", 3]
a.compact          # => [1, 2, 2, "", false, 3]
a.compact_blank    # => [1, 2, 2, 3]

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 ©