0
0
Rubyprogramming~5 mins

Find/detect for first match in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the find method do in Ruby?
The find method returns the first element in a collection that matches a given condition. If no element matches, it returns nil.
Click to reveal answer
beginner
How is detect related to find in Ruby?
In Ruby, detect is an alias for find. Both methods do exactly the same thing: return the first matching element.
Click to reveal answer
beginner
What will [1, 2, 3, 4].find { |n| n > 2 } return?
It will return 3, because 3 is the first number in the array greater than 2.
Click to reveal answer
beginner
What happens if no element matches the condition in find?
If no element matches, find returns nil.
Click to reveal answer
intermediate
Can find be used on hashes in Ruby?
Yes, find can be used on hashes. It returns the first key-value pair (as a two-element array) that matches the condition.
Click to reveal answer
What does find return if no element matches the condition?
Anil
BAn empty array
CAn error
DThe whole collection
Which method is an alias for find in Ruby?
Aselect
Bdetect
Cmap
Deach
What will [10, 20, 30].find { |x| x < 15 } return?
A20
B30
Cnil
D10
Can find be used on a hash to find a key-value pair?
ANo, it raises an error
BNo, it only works on arrays
CYes, it returns the first matching pair as an array
DYes, but it returns only the key
What is the difference between find and select?
A<code>find</code> returns first match, <code>select</code> returns all matches
B<code>find</code> returns all matches, <code>select</code> returns first match
CThey are the same
D<code>select</code> returns nil if no match, <code>find</code> raises error
Explain how the find method works in Ruby and give an example.
Think about searching for the first item that fits a rule.
You got /3 concepts.
    Describe the relationship between find and detect in Ruby.
    They are two names for the same method.
    You got /3 concepts.