search次のステートメントは、変数searchが定義されていない場合に空の文字列を割り当てます。
search = "" unless search
この割り当てが行われていなかったら、 with メッセージRegexp.newがスローされていたでしょう。検索が定義されていない場合は、メッセージ undefined local variable or method 'search'...がスローされていました。TypeErrorno implicit conversion of nil into StringNameError
次のステートメントでは:
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 = []
これが理にかなっていることを願っています。