Saturday, 8 February 2014

Reversing The Elements In A Ruby Array

So you've got your Ruby array and you want to reverse the elements in it! With the Ruby programming this task is easily accomplished with the following code. First off go and create an array in irb something like this.

my_array = ['mark','dave',1,2,3,'x']

Next we will use the reverse command on this array like so:

puts my_array.reverse

This will print the following output to your screen.


Notice here that this output has been printed out like a list. The reason for this is that we used 'puts' to output it. If you want to see the output of your array printed on the same line, simply substitute the 'puts' command for the Ruby 'print' command like so.

print my_array.reverse

["x", 3, 2, 1, "dave", "mark"]

And hey voila Ruby will print the output on the same line!

No comments:

Post a Comment