How do I return an array of integers from n to 1 where n>0? I wrote this code:
def reverse_seq(num)
reverse_seq = []
[].reverse { |num| num > 0; num = 1 }
return []
end
Thanks!
CodePudding user response:
Or
(1..5).to_a.reverse
#=> [5, 4, 3, 2, 1]
Or if you want to iterate over those elements in a next step anyway, use reverse_each
(1..5).reverse_each { |i| puts i }
#=> 5
4
3
2
1
CodePudding user response:
You could create an enumerator via downto
that goes from n
down to 1
and turn that into an array:
n = 5
n.downto(1).to_a
#=> [5, 4, 3, 2, 1]
or you could call Array.new
with a block and calculate the value:
n = 5
Array.new(n) { |i| n - i }
#=> [5, 4, 3, 2, 1]
or you could traverse a range from n
to 1
by passing -1
to step
:
n = 5
(n..1).step(-1).to_a
#=> [5, 4, 3, 2, 1]