假設一個數組元素的索引我有一個數組如何獲得包含特定字符串
["70 percent chance of rain", " 35 percent chance of snow"]
我將如何得到它包含"rain"
元素的索引?
假設一個數組元素的索引我有一個數組如何獲得包含特定字符串
["70 percent chance of rain", " 35 percent chance of snow"]
我將如何得到它包含"rain"
元素的索引?
你必須使用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
我知道這是不是你問,但你可以把它變成一個哈希:'天氣= {:雨=> 70:雪=> 70}'然後獲取像這樣的元素:'weather [:snow]' – depa
也許是這樣,但我試圖幫忙。不需要粗魯。 – depa