I know I'm not the first person to get stumped by how to get Ruby to
change an object in a method.
I want to do:
method a1 or a1.method
I can do
a1 = method a1
but amongst other things that creates a new object.
a1 = [1,2]
puts " #{a1} # 12
def myswap1(a2)
a3 = [0,0]
a3[0] = a2[1]
a3[1] = a2[0]
a2 = a3
end
myswap1 a1
puts " #{a1} " # 12
Ruby passes in a1, so at the start of the method a2 is the same
reference as a1. However when I assign a1 = a3, a1 becomes a different
reference and disappears when the method terminates.
So my first question is why won't Ruby let me do this:
a1 = [1,2]
public
def myswap5
a3 = [0,0]
a3[0] = self[1]
a3[1] = self[0]
self = a3
end
a1.myswap5 # gives error message: Can't change the value of self
My second question is from this:
a1 = [1,2]
def myswap6(a2)
a2.reverse!
end
myswap6 a1
puts " #{a1}" #21
What magic is reverse! using, and how can I avail myself of it?
···
--
Posted via http://www.ruby-forum.com/.