Complete the code to select even numbers from the array.
numbers = [1, 2, 3, 4, 5] even_numbers = numbers.select { |n| n.[1] }
odd? instead of even? selects odd numbers.nil? or zero? causes errors or wrong results.The select method filters elements for which the block returns true. Using even? selects even numbers.
Complete the code to filter words longer than 4 characters.
words = ['cat', 'elephant', 'dog', 'lion'] long_words = words.select { |word| word.length [1] 4 }
<= selects words shorter or equal to 4 characters.== selects words exactly 4 characters long.The block should return true for words longer than 4 characters, so use >.
Fix the error in the code to select numbers divisible by 3.
numbers = [3, 5, 9, 10] divisible_by_three = numbers.select { |num| num [1] 3 == 0 }
mod or div causes errors because they are not Ruby operators.remainder is a method but requires different syntax.The modulo operator % returns the remainder. Checking num % 3 == 0 finds numbers divisible by 3.
Fill both blanks to create a hash of words and their lengths, filtering words shorter than 5 characters.
words = ['apple', 'bat', 'car', 'dog'] lengths = words.select { |word| word.length < 5 }.map { |[1]| [[1], [2]] }.to_h
The hash keys are words (word) and values are their lengths (word.length), filtering words shorter than 5.
Fill all three blanks to select words starting with 'a' and convert them to uppercase.
words = ['apple', 'banana', 'avocado', 'cherry'] result = words.select { |[1]| [2].start_with?('[3]') }.map(&:upcase)
The block variable is word. We check if word starts with 'a'. Then we convert selected words to uppercase.