I wrote some code:
a = 4
b = 7
def swaps(g, f)
g ^= f; f ^= g; g ^= f
end
swaps(a, b)
p a, b
I thought I wanted result: a value is 7, b value is 4, but I got result:
4, 7
I wrote some code:
a = 4
b = 7
def swaps(g, f)
g ^= f; f ^= g; g ^= f
end
swaps(a, b)
p a, b
I thought I wanted result: a value is 7, b value is 4, but I got result:
4, 7
You do not have access to those local variables inside your method.
You can play with it by passing binding but this shouldn't be used in real life:
Objects of class
Bindingencapsulate the execution context at some particular place in the code and retain this context for future use.
def change(local_variable_name, binding, new_value)
binding.local_variable_set(local_variable_name, v)
end
Test:
a = 1
a #=> 1
change(:a, binding, 2) #=> 2
a #=> 2
Your case:
def swap(first, second, binding)
old_first = binding.local_variable_get(first)
old_second = binding.local_variable_get(second)
binding.local_variable_set(first, old_second)
binding.local_variable_set(second, old_first)
end
a = 1
b = 2
swap(:a, :b, binding)
a #=> 2
b #=> 1
Reference:
Better I read comments before! Credits to Jordan Running and Johan Wentholt
I leave this post just to point out these solutions.
Maybe parallel assignment can do it, instead of defining a method:
a = 4
b = 7
a, b = b, a
p a #=> 7
p b #=> 4
Or, if it sounds clearer:
def swap(a, b)
return b, a
end
a, b = swap(a, b)