Elliot
Elliot

Reputation: 13845

reversing the order of an array in ruby

I have the following array [12,16,5,9,11,5,4] it prints: 12,16,5,9,11,5,4.

I want it to print: 4,5,11,9,5,16,12

When I did array.reverse it printed:

4,5,11,9,5,61,21

It reversed individual numbers - any idea how I can stop that?

Upvotes: 40

Views: 64115

Answers (5)

Sean Hill
Sean Hill

Reputation: 15056

a = [12,16,5,9,11,5,4]
# => [12, 16, 5, 9, 11, 5, 4]
a.reverse
# => [4, 5, 11, 9, 5, 16, 12]

I'm not seeing what you're seeing.

Edit: Expanding on what Ben noticed, you may be reversing a string.

"12,16,5,9,11,5,4".reverse
# => "4,5,11,9,5,61,21"

If you have to reverse a string in that manner, you should do something like the following:

"12,16,5,9,11,5,4".split(",").reverse.join(",")
# => "4,5,11,9,5,16,12"

Upvotes: 83

Will Bees
Will Bees

Reputation: 1

arr1 = [12,16,5,9,11,5,4]

i = 0
arr2 = []

arr1.length.times do
  arr2 << arr1.reverse[i]
  i += 1
end

p arr2

>>[4, 5, 11, 9, 5, 16, 12]

Upvotes: 0

RubyFanatic
RubyFanatic

Reputation: 2281

If your array is an actual string, try this:

"12,16,5,9,11,5,4".split(',').reverse

Hope that solves your problem!

Upvotes: 5

jjoelson
jjoelson

Reputation: 5981

Are you trying to reverse the list in place? If so then do:

>> arr = [12,16,5,9,11,5,4]
=> [12, 16, 5, 9, 11, 5, 4]
>> arr.reverse!
=> [4, 5, 11, 9, 5, 16, 12]
>> arr
=> [4, 5, 11, 9, 5, 16, 12]

Otherwise:

>> arr_rev=arr.reverse
=> [4, 5, 11, 9, 5, 16, 12]
>> arr_rev
=> [4, 5, 11, 9, 5, 16, 12]

Upvotes: 5

Ben Marini
Ben Marini

Reputation: 2608

Sounds like your array is actually a String

Upvotes: 16

Related Questions