给定:
my_array = ['america', 'bombay', 'bostwana', 'cameroon']我可以找到第一个以'bo'开头的元素的索引
my_array.find_index { |l| l.start_with? 'bo' }我如何定位所有这样的元素?
发布于 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
复制相似问题