+ 3
Dear friends. I am confused about this code. Take a look and explain me. Its about reversing arrays in Ruby.
8 Réponses
+ 12
arr = [1,2]
print arr
#prints Array arr
puts "\n\n"
print arr.reverse!
#prints reversed Array arr and changes the value of arr to the output
puts "\n\n"
print arr
#Again prints Array arr but with new value
puts "\n\n"
print arr.reverse!.reverse
#Reverses the changed Array and changes the value of arr with output + reverses the changed Array with changing its value
puts "\n\n"
print arr.reverse!.reverse + arr
#Reveres the changed Array and changes its value + reverses the Array without changing its value + concates (joins) the Array arr to the Array arr OR itself
#A bit complicated due to #.reverse!
+ 6
@Uttam What you don't understand ?
+ 5
hey Bro! @ekansh I understood but not completely. thank you for the explanation.
+ 4
sir but last line how the last line changed ?
+ 4
at line 8 of my code :
arr.reverse!.reverse
and at line 10 of the code
how the values changed of
arr.reverse!.reverse + arr
this is perplexing...
+ 4
#arr is 2,1
arr.reverse!.reverse # prints 2,1 but since reverse! affects the arr it is 1, 2 now
# arr is 1,2
arr.reverse!.reverse # prints 1,2 but since reverse! affects the arr it is 2,1 again
for the print statement alone double reversing restores the order but one reverse affects the arr the other makes a copy
+ 3
reverse! reverses the actual array so if you have:
a =[ 1,2]
a.reverse!
# a is [2,1] now
but reverse without ! returns a new array which is the old one but reversed so:
a = [1,2]
a.reverse
# a is still [1,2]
using this knowledge you can do the reverses step by step and you get to the printed result
+ 3
at line 8
arr.reverse!.reverse #21
at line 10
arr.reverse!.reverse #12
why? Just explain only these two lines?