迭代以特定字母

时间:2017-10-04 05:02:28

标签: arrays ruby string methods

挣扎于这个概念。

例如:

names = ["Steve", "Mason", "John", "Sarah"]

如果我想仅为名字以字母开头的人输出一些文字" S"使用每种方法,我该怎么做?

pets = ["Scooby", "Soco", "Summer", "Pixie", "Wilson", "Mason","Baron", "Brinkley", "Bella"] 
(1..9).each {|pets| 
  def start_with? 
    if pets.start_with? "S"
      puts "My name starts with an S for super!" 
    else 
     puts "I’m still pretty special too!" 
    end 
  end
 }

4 个答案:

答案 0 :(得分:1)

使用each的基本方法:

names = ['Steve', 'Mason', 'John', 'Sarah']
names.each do |name|
  puts 'some text' if name.start_with?('S')
end

您可以详细了解each herestart_with here

(可能有更快的方法来确定字符串是否以单个字符开头,但我喜欢这种方法非常自我记录。)

答案 1 :(得分:1)

您也可以手动检查每个宠物名称的第一个字母,而不是使用 starts_with?

def pets_that_start_with_s(pets_array)
  pets_array.each do |pet|
    if pet[0].upcase == 'S'
      puts "My name is #{pet}, it starts with an S for Super!" 
    else 
      puts "My name is #{pet}, I’m still pretty special too!" 
    end
  end
end

pets = ["Scooby", "Soco", "Summer", "Pixie", "Wilson", "Mason","Baron", "Brinkley", "Bella"]

pets_that_start_with_s(pets)

<强>输出:

My name is Scooby, it starts with an S for Super!
My name is Soco, it starts with an S for Super!
My name is Summer, it starts with an S for Super!
My name is Pixie, I’m still pretty special too!
My name is Wilson, I’m still pretty special too!
My name is Mason, I’m still pretty special too!
My name is Baron, I’m still pretty special too!
My name is Brinkley, I’m still pretty special too!
My name is Bella, I’m still pretty special too!
添加了

N.B。 upcase以确保宠物名称的大小写没有问题。

答案 2 :(得分:0)

您需要control expression

names.each { |name| puts name if name[0] == 'S' }
#Steve
#Sarah

如果第一个字母为'S',则只打印name(通过puts。如果您不必使用each,则可以执行以下操作:

puts names.grep(/\AS/)

答案 3 :(得分:0)

我们可以使用正则表达式来解决这个问题:

names = ["Steve", "Mason", "John", "Sarah"]
names.each do |name| 
  puts name if name =~ /^s/ 
end