![](/img/trans.png)
[英]How to reject an element from an array which also contains hashes, in Ruby?
[英]How to get the index of an element of an array which contains a specific string
假设我有一个数组
["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
任何元素中都不存在“不存在”,因此它将返回nil
index = array.index { |x| x.include?('not present') } # gives nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.