If, when given an array and inclusion criterion, one wishes to construct an array that contains those elements of the first array that satisfy the inclusion criterion, one generally uses the method Array#select or Array#reject, whichever is more more convenient.
Suppose arr
is a variable that holds the given array and include_element?
is a method that takes one argument, an element of arr
, and returns true
or false
, depending on whether the inclusion criterion is satisified for that element. For example, say the array comprises the integers 1
through 6
and the inclusion criterion is that the number is even (2
, 4
and 6
). We could write:
arr = [1,2,3,4,5,6]
def include_element?(e)
e.even?
end
include_element?(2)
#=> true
include_element?(3)
#=> false
arr.select { |e| include_element?(e) }
#=> [2, 4, 6]
The method include_element?
is so short we probably would substitute it out and just write:
arr.select { |e| e.even? }
Array#select passes each element of its receiver, arr
, to select
's block, assigns the block variable e
to that value and evaluates the expression in the block (which could be many lines, of course). Here that expresssion is just e.even?
, which returns true
or false
. (See Integer#even? and Integer#odd?.)
If that expression evaluates as a truthy value, the element e
is to be included in the array that is returned; if it evaluates as a falsy value, e
is not to be included. Falsy values (logical false) are nil
and false
; truthy values (logical true) are all other Ruby objects, which of course includes true
.
Notice that we could instead write:
arr.reject { |e| e.odd? }
Sometimes the inclusion criterion consists of a compound expression. For example, suppose the inclusion criterion were to keep elements of arr
that are both even numbers and are at least 4
. We would write:
arr.select { |e| e.even? && e >= 4 }
#=> [4, 6]
With other criteria we might write:
arr.select { |e| e.even? || e >= 4 }
#=> [2, 4, 5, 6]
or
arr.select { |e| e < 2 || (e > 3 && e < 6) }
#=> [1, 4, 5]
&&
(logical 'and') and ||
(logical 'or') are operators (search "operator expressions"). As explained at the link, most Ruby operators are actually methods, but these two are among a few that are not.
Your problem now reduces to the following:
arr.select { |str| <length of str is at least 5> && <last character of str is 'y'> }
You should be able to supply code for the <...>
bits.