0

)私は非常に優れたウェブサイトコードスクールでルビーを学んでいますが、その例の1つで、背後にある方法とロジックがわかりません。誰か説明してもらえますか?

どうもありがとう ;-)

ここにコードがあります

search = "" unless search 
games = ["Super Mario Bros.", "Contra", "Metroid", "Mega Man 2"]
matched_games = games.grep(Regexp.new(search))
puts "Found the following games..."
matched_games.each do |game|
  puts "- #{game}"
end

1行目と3行目がよくわからない

search = "" unless search 

matched_games = games.grep(Regexp.new(search))
4

3 に答える 3

1

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 = []

これが理にかなっていることを願っています。

于 2013-08-22T09:51:11.263 に答える
0

vinodadhikary はすべてを言いました。OPが言及した構文が気に入らないだけです

search = "" unless search 

これはもっといいです

search ||= ""
于 2013-08-22T09:55:12.940 に答える
0

検索はRegexpまたは nil のインスタンスである必要があります。最初の行の検索では、最初に nil に等しい場合、空白の文字列に設定されます。

3 番目の文字列Matched_gamesは、指定された正規表現に一致する文字列の配列に設定されます ( http://ruby-doc.org/core-2.0/Enumerable.html#method-i-grep )

于 2013-08-22T09:45:13.160 に答える