Thallius Thallius - 6 months ago 37
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


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!


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

To this end you can use Array#select: { |word| word.start_with?('b') }
#=> ["bread", "beer"]