Andy Harvey
Andy Harvey

Reputation: 12653

How to extract records at position x from an array?

In Rails (or Ruby), is it possible to target and manipulate items at a certain position within an array.

For example, say I have defined an array that cannot exceed 10 records.

@array = Model.where(:my_query = something).order(:my_order).first(10)

Now I want to do something with the first 5 records, and something else with the last five. I could use

@array.first(5)
@array.last(5)

but this falls apart if :my_query returns less than 10 records—i.e. there will be overlap.

@array.at(1)

returns a single position, but what if I need a range of positions. I'm looking for something like

@array.position(1..5)
@array.position(6..10)

Does something like this exist? I'm not sure what search terms I should be Googling?

Upvotes: 0

Views: 69

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107718

You want something like this:

first = @array[0..4]
last = @array[5..9]

That will return the first five and the last five elements from the array in two separate variables. If you do it this way and you will not get any overlap.

Upvotes: 1

Related Questions