search
次のステートメントは、変数search
が定義されていない場合に空の文字列を割り当てます。
search = "" unless search
この割り当てが行われていなかったら、 with メッセージRegexp.new
がスローされていたでしょう。検索が定義されていない場合は、メッセージ undefined local variable or method 'search'...がスローされていました。TypeError
no implicit conversion of nil into String
NameError
次のステートメントでは:
matched_games = games.grep(Regexp.new(search))
games.grep(pattern)
パターンに一致するすべての要素の配列を返します。詳細については、grepを参照してください。 文字列または正規表現パターンのいずれかであるRegexp.new(search)
、指定された変数から新しい正規表現を構築します。詳細については、 Regexp::newsearch
を参照してください。
たとえば、検索が""
(空の文字列)の場合、検索 = 'スーパー マリオ ブラザーズ' の場合、Regexp.new(search)
が返されます。//
をRegexp.new(search)
返します/Super Mario Bros./
。
次にパターンマッチング:
# For search = "", or Regexp.new(search) = //
matched_games = games.grep(Regexp.new(search))
Result: matched_games = ["Super Mario Bros.", "Contra", "Metroid", "Mega Man 2"]
# For search = "Super Mario Bros.", or Regexp.new(search) = /Super Mario Bros./
matched_games = games.grep(Regexp.new(search))
Result: matched_games = ["Super Mario Bros."]
# For search = "something", or Regexp.new(search) = /something/
matched_games = games.grep(Regexp.new(search))
Result: matched_games = []
これが理にかなっていることを願っています。