address = [1,2,3]
p address
new_address = address.reverse!
p new_address
p address.reverse!
Prints:
[1,2,3]
[3,2,1]
[1,2,3]
I don't understand why the last print out is 1,2,3 if it is meant to print the address in reverse, the address is 1,2,3
I expected the last line to be [3,2,1].
CodePudding user response:
To understand why this behavior you need to know what the !
means:
It indicate to the interprete that has to operate over the object and make the changes on it first and then return the result.
So address is:
address = [1,2,3]
When you call this:
new_address = address.reverse! # Address is [3,2,1]
And last:
p address.reverse! # address is [1, 2, 3]
Here the base is to understand that !
is always modifiying the object itself.
CodePudding user response:
In ruby when you have a !
at the end of the method call that means that it changes the recipient as well.
So new_address = address.reverse!
not just assigned the reverted value to new_address
but also to address
.
I updated your code to make it more visible:
address = [1,2,3]
p address
new_address = address.reverse! # [3,2,1]
p address # [3,2,1]
p new_address # [3,2,1]
p address.reverse! # [1,2,3]
What you wanted to use is the same method but without !
address = [1,2,3]
p address
new_address = address.reverse
p new_address
p address.reverse
More info: http://ruby-for-beginners.rubymonstas.org/objects/bangs.html
CodePudding user response:
It's all about the bang (!)
in ruby.
address = [1,2,3]
p address
#> [1,2,4]
address.reverse
p address
#> [1,2,3]
address.reverse!
p address
#> [3,2,1]
Bang or exclamation mark means that you are making a permanent saved change in your code.
some more examples:
#without Bang (!).
name = "Ruby Monstas"
puts name.downcase
#> ruby monstas
puts name
#> Ruby Monstas
# With Bang(!) Operator
name = "Ruby Monstas"
puts name.downcase!
#> ruby monstas
puts name
#> ruby monstas