Practice Problems: Truthiness
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_array = arr.select do |n| n + 1 end p new_array
line 6, we are calling the method
p passing in local variable
new_array to it as an argument. This method output and return the array object pointed by the variable, namely
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11].
line 1, we are initializing the local variable
arr to the array object with element 1 to 10:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
line 3, we are intializing
new_array with the result of the method
line 3-5, the method
select is called on the local variable
arr passing in the
do..end block as an argument.
select iterates over each element in the array and passes it to the block as the parameter
1 is added to
n. As it’s the last line of the block, the result is returned.
select considers if the returned value of the block evaluates to
true or not. If it is, the method add the value to a new array.
This problem demonstrates the concept of truthiness. In Ruby, everything except
nil evaluates to
true. In the case above, the block never returns
nil, therefore each value returned by the block are evaluated to
true and therefore all returned to the new array created by
select. This new array is used as the array object used in the initialization of
arr = [1, 2, 3].any? do |num| "hi" end p arr
This code outputs
true and return
line 5 we are calling the method
p passing in the local variable
The local variable
arr is defined on
line 1. It is defined with the return value of the method call
any? on object array
[1, 2, 3] passing in a
true when at least one block passed to it returns
true. Here, it return
true because on
line 1-3, the
do..end block return the local string
"hi" which always evaluates to true.
This problem demonstrates how the method
any? works, as well as truthiness in Ruby.