Sunday, April 3, 2011

Swapping variables

Today I was learning about binding, and the example showed in that page is how to use binding to swap variables.

The text ended up with
swap(ref{:a}, ref{:b})

However, I show here a less verbose (and simpler) swap (without binding, references, etc.):

swap = lambda do |x, y|
  eval "#{x}, #{y} = #{y}, #{x}"

a = 'hihaha'
b = 33

swap[:a, :b]

puts a         #=> 33
puts b         #=> 'hihaha'

I guess the former example is still valid as didatic text about binding.

No comments:

Post a Comment