Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reversing the order of an array in ruby

Tags:

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?

like image 676
Elliot Avatar asked Mar 09 '11 04:03

Elliot


People also ask

How do you reverse an array order?

reverse() The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first.

How do you sort an array in Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.


4 Answers

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"
like image 169
Sean Hill Avatar answered Sep 30 '22 19:09

Sean Hill


Sounds like your array is actually a String

like image 26
Ben Marini Avatar answered Sep 30 '22 20:09

Ben Marini


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]
like image 43
jjoelson Avatar answered Sep 30 '22 20:09

jjoelson


If your array is an actual string, try this:

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

Hope that solves your problem!

like image 40
RubyFanatic Avatar answered Sep 30 '22 20:09

RubyFanatic