2013-05-30 49 views
-1

假設一個數組元素的索引我有一個數組如何獲得包含特定字符串

["70 percent chance of rain", " 35 percent chance of snow"] 

我將如何得到它包含"rain"元素的索引?

+0

我知道這是不是你問,但你可以把它變成一個哈希:'天氣= {:雨=> 70:雪=> 70}'然後獲取像這樣的元素:'weather [:snow]' – depa

+0

也許是這樣,但我試圖幫忙。不需要粗魯。 – depa

回答

4

你必須使用index方法

array = ["70 percent chance of rain", " 35 percent chance of snow"] 
index = array.index { |x| x.include?('rain') } # gives 0 
index = array.index { |x| x.include?('snow') } # gives 1 

注: - 這會給你一個字符串中第一次出現的索引,如果字符串不存在將返回nil

爲前: - percent是存在於所述陣列元件,從而它會返回0

index = array.index { |x| x.include?('percent') } # gives 0 

「不prese NT」不存在任何元素,因此它會返回nil

index = array.index { |x| x.include?('not present') } # gives nil 
+1

你也可以使用正則表達式array.index {| i |我=〜/雨/}'。不知道哪一個會更快。 – depa

+0

thx哥們。這個很酷。 :) – rony36

+1

@depa: - 我同意你應該使用適合你的正則表達式,因爲它比'include? – Salil

相關問題