0

)我正在通过非常好的网站代码学校学习 ruby​​,但是在他们的一个示例中,我不明白背后的方法和逻辑,有人可以解释一下吗?

太感谢了 ;-)

这是代码

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变量 ifsearch未定义。

search = "" unless search 

如果未完成此分配,Regexp.new则会抛出TypeError带有消息no implicit conversion of nil into String,或者如果未定义搜索,则NameError使用消息未定义的局部变量或方法“搜索”...

在以下声明中:

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

games.grep(pattern)返回与模式匹配的每个元素的数组。有关详细信息,请参阅grepRegexp.new(search)从提供的变量构造一个新的正则表达式,该search变量可以是字符串或正则表达式模式。同样,有关更多详细信息,请参考Regexp::new

所以说例如搜索是""(空字符串),然后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,则在第一行搜索设置为空白字符串。

在第三个字符串中, matched_games设置为与给定正则表达式匹配的字符串数组(http://ruby-doc.org/core-2.0/Enumerable.html#method-i-grep

于 2013-08-22T09:45:13.160 回答