0

I have an array @dates, that are UTC dates, and in increasing order. I want to flip the indices of the array so that the dates are in descending order. I am familiar with JS an Java, and don't know how to either use a pointer/index counter in ruby.

@dates = [//dates are in here already]

@reverseDates = []
@dates.each do |d|
  @reverseDates << @dates.last
end

@dates = @reverseDates

Part of the issue as well is that I think it is duplicating the last index of @dates, not moving it to the other array when it pushes.

So I got it it working by prepending the array, but how do you include index counters in Ruby to accomplish this?

@reverseDates = []
@dates.each do |d|
  @reverseDates.unshift(d)
end

@dates = @reverseDates
2
  • In the first example @dates.last never changes in the each because @dates never changes in the each. See Enumerable#each_with_index for how to iterate with an index; however, this is not the real problem, nor the real solution. Commented Dec 24, 2012 at 3:45
  • I recommend reading the full API of the Enumerable module from A to Z, each one of these methods is so powerful! Commented Dec 24, 2012 at 4:40

1 Answer 1

6

Ruby has reversing an array built in:

@dates.reverse!

From http://ruby-doc.org/core-1.8.7/Array.html#method-i-reverse-21

Sign up to request clarification or add additional context in comments.

1 Comment

I would recommend using reverse as I find that reducing side-effects creates easier-to-follow code and reduces surprises.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.