当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - How to choose based on specific multiples of indexes from array

问题描述:

This is probably very basic question.

Suppose I have an array with 19 items [0,1,2,3,4..19]. How could I selecting only the ones with the index count that are multiples of a given number i.e. 2?

Updated: Supposed this code is intended to use for columns. How to manage to get indexes that would be of first column given that all are multiple of one?

网友答案:

Select elements which are multiples of a given number (works if your elements equal the index):

ary.select { |element| element % 2 == 0 }

In this special case, you can also use symbol to proc:

ary.select &:even?

If your elements are different from the indices, group in pairs of 2 and use the first element:

ary.each_slice(2).map { |slice| slice[0] }
网友答案:

Check out Enumerable#select (Array includes Enumerable). You can do this:

1.9.3p392 :001 > a = [1,2,3,4,5,6]
 => [1, 2, 3, 4, 5, 6]
1.9.3p392 :002 > a.select {|n| n % 2 == 0}
 => [2, 4, 6]

select will filter the array, picking out anything for which the block returns true. In this case, using the mod (%) operator to find elements divisible by 2.

网友答案:

If I understand you correctly you want to take only the even indices. Try using each_index.

arr = (0..19).to_a
arr.each_index { |x| puts arr[x] if x % 2 == 0 }

This prints:

0
2
4
6
8
10
12
14
16
18

If you want the even elements of the array you could use find_all too.

arr.find_all { |e| e.even? }
网友答案:
(1..19).to_a.select{|e| e.%(2).zero?}

This is slightly faster than using == 0.

分享给朋友:
您可能感兴趣的文章:
随机阅读: