Introduction
Select or filter helps you pick only the items you want from a list, like choosing your favorite fruits from a basket.
array.select { |item| condition } # or array.filter { |item| condition }
select and filter do the same thing in Ruby.{ } tells Ruby which items to keep.[1, 2, 3, 4, 5].select { |n| n.even? }
['apple', 'banana', 'avocado'].filter { |fruit| fruit.start_with?('a') }
[10, 15, 20, 25].select { |num| num > 15 }
numbers = [1, 2, 3, 4, 5, 6] even_numbers = numbers.select { |n| n.even? } puts "Even numbers: #{even_numbers.join(', ')}"
select returns a new array.select returns an empty array.select or filter with a block that returns true for items you want to keep.select method do in Ruby when used on an array?selectselect method filters elements from an array based on a condition given in a block.selectselect filters and returns new array [OK]nums using select?select method requires a block with a parameter and a condition, usually written as { |param| condition }.|n| and condition n % 2 == 0. Other options have syntax errors or wrong block usage.numbers = [1, 2, 3, 4, 5]
even_numbers = numbers.select { |num| num.even? }
puts even_numbers.inspectselect block conditionnum.even? which returns true for even numbers only.words = ["cat", "dog", "elephant", "fox"] long_words = words.select |word| word.length > 3 puts long_words.inspect
select |word| word.length > 3 without curly braces or do..end, which is invalid syntax.select { |word| word.length > 3 } or select do |word| word.length > 3 end.scores = { alice: 50, bob: 75, carol: 40, dave: 90 }, how do you select only the key-value pairs where the score is 50 or more?select on a hash, the block receives two parameters: key and value.score >= 50.|name, score| score >= 50. The other options have wrong parameters or conditions.Pass the test and this pattern moves unknown