Martin
Martin

Reputation: 11336

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?

Upvotes: 2

Views: 203

Answers (4)

sawa
sawa

Reputation: 168081

(1..19).to_a.select{|e| e.%(2).zero?}

This is slightly faster than using == 0.

Upvotes: 0

squiguy
squiguy

Reputation: 33370

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? }

Upvotes: 1

Huluk
Huluk

Reputation: 874

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] }

Upvotes: 2

Jim Stewart
Jim Stewart

Reputation: 17323

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.

Upvotes: 2

Related Questions