如何在if语句中捕获greps返回值以便在块内使用?
colors = ["red", "blue", "white"]
if color = colors.grep(/^b/) # Would be nice to capture the color blue
puts "Found #{color.first}." # with the regex, and pass it down to block
else
puts "Did not find the first color."
end
我们怎么能以不同的方式表达出来?
答案 0 :(得分:4)
你可以这样做:
if (found = colors.grep(/^b/)).empty?
puts "Did not find the first color."
else
puts "Found #{found.first}."
end
捕获数组并一次检查它是否为空。如果您只想要found.first
,那么我会选择Jakub的。
答案 1 :(得分:1)
我不确定你要做什么。但是如果你希望color
成为if条件中的字符串"blue"
,如果找不到任何内容会触发else条件,你可以试试这个:
colors = ["red", "blue", "white"]
if color = colors.grep(/b/).first
puts "Found #{color}."
else
puts "Did not find the first color."
end
答案 2 :(得分:0)
既然你问“我们怎么能以不同的方式表达”,那么这是另一种选择。
matches = colors.select{ |c| c.start_with? "b"}
这将为您提供一系列匹配的颜色(以字母“b”开头的颜色)。然后,您可以执行以下操作:
if matches.empty?
puts "Did not find the first color."
else
puts "Found #{matches.first}."
end