+ 3

Dear friends. I am confused about this code. Take a look and explain me. Its about reversing arrays in Ruby.

https://code.sololearn.com/cTkT6M458KOC/?ref=app

18th Oct 2017, 4:10 PM
Uttam
Uttam - avatar
8 Respostas
+ 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!
18th Oct 2017, 4:24 PM
Ekansh
+ 6
@Uttam What you don't understand ?
18th Oct 2017, 4:38 PM
Ekansh
+ 5
hey Bro! @ekansh I understood but not completely. thank you for the explanation.
18th Oct 2017, 4:31 PM
Uttam
Uttam - avatar
+ 4
sir but last line how the last line changed ?
18th Oct 2017, 4:19 PM
Uttam
Uttam - avatar
+ 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...
18th Oct 2017, 4:22 PM
Uttam
Uttam - avatar
+ 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
18th Oct 2017, 4:45 PM
Chrizzhigh
Chrizzhigh - avatar
+ 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
18th Oct 2017, 4:18 PM
Chrizzhigh
Chrizzhigh - avatar
+ 3
at line 8 arr.reverse!.reverse #21 at line 10 arr.reverse!.reverse #12 why? Just explain only these two lines?
18th Oct 2017, 4:40 PM
Uttam
Uttam - avatar