Reverse an array without using a loop in ruby

后端 未结 8 452
时光说笑
时光说笑 2021-01-24 12:12

I have a coding challenge to reverse a an array with 5 elements in it. How would I do this without using the reverse method?

Code:

def reverse(array)
 a         


        
8条回答
  •  后悔当初
    2021-01-24 12:43

    One thought :-

    ary = ["a", 1, "apple", 8, 90]
    ary.values_at(*(ary.size-1).downto(0))
    # => [90, 8, "apple", 1, "a"]
    

    ary.size.downto(0) gives #. And *# is just a Enumerable#to_a method call which splats the Enumerator to [4, 3, 2, 1, 0]. Finally, Array#values_at is working as documented.

提交回复
热议问题