Ruby: How to find all indices of elements that match a given condition?
来源:互联网 发布:快手喊麦都用什么软件 编辑:程序博客网 时间:2024/05/15 23:46
Given an array, how would you find all indices of elements those match a given condition?
For example, say we have:
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
To find all indices where the item is x
, I could do:
arr.each_with_index.map { |a, i| a == 'x' ? i : nil }.compact # => [0, 2, 6]
or
(0..arr.size-1).select { |i| arr[i] == 'x' } # => [0, 2, 6]
Is there a nicer way to achieve this?
Ruby 1.9:
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']p arr.each_index.select{|i| arr[i] == 'x'} # =>[0, 2, 6]
find Index of first Matching Element
a=[100,200,300]a.index{ |x| x%3==0 }
0 0
- Ruby: How to find all indices of elements that match a given condition?
- find all pairs of elements in a balanced BST that sum to a certain number
- Given an array of integers, return indices of the two numbers such that they add up to a specific ta
- Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive
- Find k closest elements to a given value
- Given a list of presentations with begin and end time that all need to use a conference room.
- How to find number of a specific integer in an array of Fixnums ruby
- [Twitter] Given a matrix with all elements sorted on each individual row and column find
- How to find child controls that are located in the template of a parent control
- Ch4.8: find all the path that a Binary tree sums up to a given value, may/maynot have parent pointer
- How to show/hide a set of elements?
- 【Leetcode】Given a binary tree, find all root-to-leaf paths whose sum equals a given number
- How can I combine elements of an array that have a common element?
- Given a sequence of numbers (or array).Find the maximum distance between all the same numbers.
- CareerCup Find all the conflicting appointments from a given list of n appointments.
- Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or
- Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthe
- [LinkedIn] Array of size n and an int k, find all elements that appear/occur more than n/k times
- 【kruskal+最小偏心距】wiki1700施工方案第二季
- 安卓简易闪光灯
- springmvc+ibatis配置环境
- eclipse导入项目出现乱码
- 黑马程序员——OC语言Protocol(协议)
- Ruby: How to find all indices of elements that match a given condition?
- github 一些实用的GitHub模式
- Android Call requires API level 11 (current min is 8)的解决方案
- GreenDAO+AndroidAnontations+TempRest协同开发
- 【摘要】图像文本检测提取算法
- 用C/C++语言实现贪吃蛇游戏
- 在网页中添加视频(HTML)
- log4j日志配置文件
- UNIX高级环境2的环境搭建