Thallius Thallius - 25 days ago 9
Ruby Question

RUBY: How can I print only the words that start with a certain letter from an Array?

-------So what I have so far is-----------

array = ["milk", "bread", "pizza", "eggs", "soda", "beer"]

def first_letter(x)
if x.start_with?(b)
puts x
end
end

first_letter(array)


Really confused on what I need to do. I've checked Ruby Docs and I still can't figure out how to single out just the words that start with "B" in my array and print them to the screen. Any help would be much appreciated!

Answer

What you want is basically select the elements, matching the condition.

To this end you can use Array#select:

array.select { |word| word.start_with?('b') }
#=> ["bread", "beer"]