如何从数组中提取字符串然后检查它的第一个字母?

时间:2012-02-08 23:24:47

标签: ruby arrays string

  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

基本上我要做的就是使用上面的代码从数组中提取一个单词,然后检查该字符串的第一个字母是否匹配。基本上它会询问用户一个字母,然后它会检查该字母与数组中每个字符串的第一个字母。标记的行应该检查字符串的第一个字母。如果它等于字母,程序将输入该条目的名称和年龄。

2 个答案:

答案 0 :(得分:5)

您的问题有点难以理解,但以下代码会选择数组中第一个字母为a的所有字符串。也许这会让你走上正轨:

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"]

答案 1 :(得分:3)

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

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

考虑Enumerable#grep方法regex