Forrest Wilkins
Forrest Wilkins

Reputation: 537

Inserting elements into new array and then deleting from old array, some elements getting ignored

I'm trying to remove pairs of the smallest and largest elements from an Array and store them in a second one. Is there a better way to do this or a Ruby method I don't know about that could accomplish something like this?

Here's my code:

nums = [1, 2, 3, 4, 5, 6]
pairs = []; for n in nums
  pairs << [n, nums.last]
  nums.delete nums.last
  nums.delete n
end

Current result:

nums
#=> [2, 4]
pairs
#=> [[1, 6], [3, 5]]

Expected result:

nums
#=> []
pairs
#=> [[1, 6], [2, 5], [3, 4]]

Upvotes: 1

Views: 74

Answers (2)

Drenmi
Drenmi

Reputation: 8777

Enumerating over an Array while deleting it's content is generally not advisible. Here's an alternative solution:

nums = *(1..6)
#=> [1, 2, 3, 4, 5, 6]

pairs = []
#=> []

until nums.size < 2 do
  pairs << [nums.shift, nums.pop]
end

pairs
#=> [[1, 6], [2, 5], [3, 4]]

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110665

Assuming nums is sorted and can be modified, I like this way because it has a mechanical feel about it:

pairs = (nums.size/2).times.map { [nums.shift, nums.pop] }
  #=> [[1, 6], [2, 5], [3, 4]] 
nums
  #=> []

I see @Drenmi has the same idea of using shift and pop.

If you don't want to modify nums, you could of course operate on a copy.

Upvotes: 5

Related Questions