0
0
Rubyprogramming~5 mins

Select/filter for filtering in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the select method do in Ruby?
The select method filters elements from a collection based on a condition. It returns a new array with elements for which the condition is true.
Click to reveal answer
beginner
How is select different from reject in Ruby?
select keeps elements where the condition is true, while reject keeps elements where the condition is false.
Click to reveal answer
beginner
Given numbers = [1, 2, 3, 4, 5], what does numbers.select { |n| n.even? } return?
It returns [2, 4] because it selects only the even numbers from the array.
Click to reveal answer
intermediate
Can select be used on hashes in Ruby? How?
Yes, select can be used on hashes. It returns a new hash with key-value pairs where the block condition is true.
Click to reveal answer
beginner
What is the return type of select when used on an array?
It returns a new array containing the filtered elements.
Click to reveal answer
What does select return when no elements match the condition?
Anil
BThe original array
CAn empty array
DAn error
Which method would you use to get elements that do NOT match a condition?
Areject
Bselect
Cmap
Deach
What will [1, 2, 3].select { |n| n > 3 } return?
A[1, 2, 3]
B[]
C[3]
Dnil
Can select change the original array?
AOnly for hashes
BYes, it modifies the original array
COnly if used with <code>!</code>
DNo, it returns a new array
Which of these is a valid use of select on a hash {a: 1, b: 2}?
A<code>.select { |k, v| v.even? }</code>
B<code>.select { |k| k == :a }</code>
C<code>.select { |v| v > 1 }</code>
D<code>.select { |k| k > 1 }</code>
Explain how the select method works in Ruby with an example.
Think about choosing items that match a rule.
You got /4 concepts.
    Describe the difference between select and reject methods in Ruby.
    One chooses what you want, the other what you don't want.
    You got /4 concepts.