给定:
my_array = ['america', 'bombay', 'bostwana', 'cameroon']我可以找到第一个以'bo'开头的元素的索引
my_array.find_index { |l| l.start_with? 'bo' }我如何定位所有这样的元素?
发布于 2016-10-14 23:30:54
如果您需要这些元素:
my_array.find { |element| element.start_with? 'bo' } # => "bombay"
my_array.select { |element| element.start_with? 'bo' } # => ["bombay", "bostwana"]如果你想要索引:
my_array.index { |element| element.start_with? 'bo' } # => 1
my_array.map.with_index.select { |element, _| element.start_with? 'bo' }.map(&:last)
# => [1, 2]发布于 2016-10-15 00:05:59
您可以使用带有条件的map.with_index,并对结果执行compact。
my_array.map.with_index{ |element, index| index if element.start_with? 'bo' }.compact它是如何工作的
地图
map将获取所有值,并将它们“映射”到在将每个项传递到给定块时返回的值。
my_array.map { |element| element.start_with? 'bo' }
# => [false, true, true, false]with_index
要获取索引值,可以使用with_index,如下所示:
my_array.map.with_index { |element, index| index }
# => [0, 1, 2, 3]
my_array.map.with_index { |element, index| index if element.start_with? 'bo' }
# => [nil, 1, 2, nil]紧凑型
然后,为了摆脱nil值,可以对返回的数组调用compact。
my_array.map.with_index{ |element, index| index if element.start_with? 'bo' }.compact
# => [1, 2]发布于 2016-10-15 00:21:08
['america', 'bombay', 'bostwana', 'cameroon']
.each_with_index # to get indices
.grep(->(e) { e.first.start_with? "bo" }) # I ❤ Enumerable#grep
.map(&:last) # get indices
#⇒ [1, 2]我发布这篇文章是为了展示很少使用的方法。Enumerable#grep接受任何用于基于三等大小写比较来选择项目的内容。
在那里传递Proc实例很酷,因为Proc有一个默认的Proc#===实现:它只是在接收器上被调用。
https://stackoverflow.com/questions/40046825
复制相似问题