LoginSignup
0
0

More than 1 year has passed since last update.

任意の文字列から特定の連続する文字列を探し、その直前の値により「True」または「False」を出力するプログラムを実装

Posted at

任意の文字列から特定の連続する文字列を探し、その直前の値により「True」または「False」を出力するプログラムを実装します。

以下の要件を満たすxyz_thereメソッドを実装します。

  • 任意の文字列から連続する文字列"xyz"を探し、その直前にピリオド(.)がない場合はTrueを出力する
  • 任意の文字列から連続する文字列"xyz"を探し、その直前にピリオド(.)がある場合はFalseを出力する
  • 上記2つの条件に当てはまらない場合はFalseを出力する

出力例

xyz_there('abcxyz') → True
xyz_there('abc.xyz') → False
xyz_there('xyz.abc') → True
xyz_there('azbycx') → False
xyz_there('a.zbycx') → False

include?メソッドを使いましょう。

include?メソッドは、指定した要素が配列または文字列に含まれているかを判定するメソッドです。

str = "foobar"
puts str.include?("bar")
#=> true
puts str.include?("hoge")
#=> false

出力例

def xyz_there(str) 
  if str.include?(".xyz")
    puts "False"
  elsif str.include?("xyz")
    puts "True"
  else
    puts "False"
  end
end

xyz_there('abcxyz')

ここ重要↓

include?を用いて、対象となる文字列が含まれているかどうかを、各条件式で判別しています。
ポイントとしては、str.include?(".xyz")の条件式をstr.include?("xyz")より前に設置することです。
例えば"abc.xyz"という文字列の場合は、str.include?("xyz")においてもtrueとなってしまうため、先に".xyz"を含むかどうかを判別する必要があります。

どうしても初心者だと puts "True"を先に書きたくなるところですが、そんなに甘くはないですね。
もっと勉強が必要だと改めて感じました。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0