简体   繁体   中英

Printing array of multi-digit elements in reverse order in ruby

How to print an array of elements in reverse order not just single digit number but also multi-digit numbers.

[2, 5, 6 7]

It should print the array elements in reverse order as 7 6 5 2 by following a space for each number.

I already wrote the code for this.

   puts "Enter the array elements"
    arr = gets.strip
    arr = arr.split(' ').map(&:to_i)
    x = arr.reverse_each {|f| }
    z = x.join(" ")
    print z.reverse

That is cool with single digit numbers, how can I reverse the multi-digit numbers in an array of inputs given by the user input like:

[45, 76, 87 ] # this should reverse the array as `87 76 45`


[556, 674, 878 ] # this should reverse the array as `878 674 556`
[8797, 7347, 9374 ] # this should reverse the array as `9374 7374 8797`

If you like one-liners:

gets.strip.split(' ').reverse.join(' ')

This will take the input 1 2 3 45 678 9 and convert it to "9 678 45 3 2 1"

Input: [8797, 7347, 9374 ]

Output: "9374 7374 8797"

arr = gets.chomp
arr = arr.split(' ').map(&:to_i)
x = arr.reverse.join(' ')
print x

Use reverse and join chained and it should return a String type that joined your reversed array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM