Thallius Thallius - 1 year ago 73
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!

Answer Source

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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download