0
0
Rubyprogramming~20 mins

Find/detect for first match in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Find/Detect Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Find the first even number in an array
What is the output of this Ruby code that finds the first even number in the array?
Ruby
numbers = [1, 3, 5, 8, 10]
result = numbers.find { |n| n.even? }
puts result
Anil
B10
C8
D1
Attempts:
2 left
💡 Hint
Remember, find returns the first element matching the condition.
Predict Output
intermediate
2:00remaining
Detect the first string longer than 4 characters
What does this Ruby code print when detecting the first string longer than 4 characters?
Ruby
words = ['cat', 'dog', 'horse', 'elephant']
result = words.detect { |w| w.length > 4 }
puts result
Ahorse
Bdog
Celephant
Dnil
Attempts:
2 left
💡 Hint
Check the length of each word in order.
Predict Output
advanced
2:00remaining
Find first hash with value greater than 10
What is the output of this Ruby code that finds the first hash with a value greater than 10?
Ruby
items = [{a: 5}, {b: 15}, {c: 8}]
result = items.find { |h| h.values.first > 10 }
puts result
A{:a=>5}
B{:c=>8}
Cnil
D{:b=>15}
Attempts:
2 left
💡 Hint
Look at the values inside each hash.
Predict Output
advanced
2:00remaining
Detect first number divisible by 7
What does this Ruby code output when detecting the first number divisible by 7?
Ruby
nums = [10, 14, 21, 28]
result = nums.detect { |n| n % 7 == 0 }
puts result
A21
B14
C28
D10
Attempts:
2 left
💡 Hint
Check each number in order for divisibility by 7.
🧠 Conceptual
expert
2:00remaining
Understanding find vs detect in Ruby
Which statement is true about the Ruby methods find and detect?
A<code>find</code> and <code>detect</code> are aliases and behave identically.
B<code>find</code> returns the first match, <code>detect</code> returns all matches.
C<code>find</code> only works on arrays, <code>detect</code> only on hashes.
D<code>detect</code> is deprecated and should not be used.
Attempts:
2 left
💡 Hint
Check Ruby documentation for these methods.