2017-10-04 9 views
0

この概念では苦労しています。例えば特定の文字で始まる名前の配列を繰り返します。

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 
} 
+0

これまでに何を試してみましたか? –

+0

ペット= ["スクービー"、 "ソコ"、 "サマー"、 "ピクシー"、 "ウィルソン"、 "メーソン"、 "バロン"、 "ブリンクリー"、 "ベラ" (1..9).each {|ペット| def start_with? if pets.start_with? "S" puts "私の名前はスーパーでSで始まります!" else puts「私はまだかなり特別です! end end } – slothy

+1

あなたのご質問はきれいにしてください。誰もあなたのexpirienceについて心配する、私たちすべてここと我々すべてが学ぶ。 https://stackoverflow.com/help/how-to-ask –

答えて

1

、あなたはまた、手動で各ペットの名前の最初の文字をチェックすることができ:

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が追加され、ペットの名前の大文字化に問題がないことを確認しました。

0

あなたはcontrol expressionが必要です

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

最初の文字は 'S' である場合にのみputs経由)nameを出力します。あなたは、あなたが行うことができますeachを使用する必要がない場合:

puts names.grep(/\AS/) 
1

eachを使用して基本的なアプローチ:

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

をあなたはeachherestart_withhereについての詳細を読むことができます。

(文字列は単一の文字で始まるが、私は、この方法は非常に自己文書化であることを好きかどうかを判断するためにはるかに高速な方法は、おそらくあります。)

+0

こんにちは、お返事ありがとうございます。これは私のために働いた。あなたのようなコードブロックを提出するにはどうすればよいですか?私はコメントでこれを行う方法を見つけることができないようです。私がしたことをあなたに見せたい。 – slothy

0

私たちは、正規表現を使用することによってこの問題を解決することができます

代わりに starts_with?を使用しての
names = ["Steve", "Mason", "John", "Sarah"] 
names.each do |name| 
    puts name if name =~ /^s/ 
end 
+1

'/ \ AS /'や '/ \ As/i'を意味しないのですか?'^'はRubyでは* line *の始めで、 '\ A'は* string *の始めです。あなたはあなたの 'S'の事件を見る必要があります。 –

関連する問題