user1179092
user1179092

Reputation: 5

How can I pull a string from an array and then check the first letter of it?

  puts "Please Enter First Initial..."
  initial = gets
  first_letter( name, age, initial)  

  def first_letter( x, y, z)
       index = 0
       while index < x.length
        --->if z == (x[index])
        puts "#{x[index]}   #{y[index]}"
        end
        index += 1
      end
    end

So essentially what I'm trying to do is use the above code to pull a word from an array and then check the first letter of that string for a match. Essentially it asks the user for a letter and then it checks that letter against the first letter of each string in the array. The marked line is supposed to check the letter against the first letter of the string. If it is equal to the letter, the program is to put the name and age of that entry.

Upvotes: 0

Views: 1392

Answers (2)

evfwcqcg
evfwcqcg

Reputation: 16365

a = %w{ axxx bxxx aaaa cccc azz }
# => ["axxx", "bxxx", "aaaa", "cccc", "azz"] 

a.grep(/^a/)
# => ["axxx", "aaaa", "azz"] 

Consider Enumerable#grep method with a little bit of regex.

Upvotes: 3

Michael Kohl
Michael Kohl

Reputation: 66867

Your question is a bit hard to understand, but the following code selects all the strings from the array where the first letter is an a. Maybe this gets you on the right track:

a #=> ["a", "b", "c", "aa", "bb", "cc", "aaa", "bbb", "ccc"] 
a.select { |x| x[0] == ?a } #=> ["a", "aa", "aaa"]
# or
a.select { |x| x.start_with? 'a' } #=> ["a", "aa", "aaa"]

Upvotes: 5

Related Questions