2012-03-23 53 views
2

如何在if語句中捕獲greps返回值以便在塊內使用?ruby​​ - 爲greps返回值賦值if語句

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 

我們如何表達這種不同?

回答

4

你可以做這樣的事情:

if (found = colors.grep(/^b/)).empty? 
    puts "Did not find the first color." 
else 
    puts "Found #{found.first}." 
end 

捕捉數組並檢查它是否爲空。如果你只想要found.first那麼我會選擇Jakub的。

+0

我接受了您的提示,並意識到這有點無意義:)現在是時候讓我猜測了。 – 2012-03-23 03:01:42

+0

@NiklasB .:不一定毫無意義,有時很好玩。 – 2012-03-23 03:17:06

1

我不太確定你想要做什麼。但是如果你想color爲字符串"blue"在if條件,如果沒有發現觸發的其他條件,你可以試試這個:

colors = ["red", "blue", "white"] 

if color = colors.grep(/b/).first 
    puts "Found #{color}." 
else 
    puts "Did not find the first color." 
end 
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