parsed.org
Dynamic Function Assignment in Ruby by Hawk-McKain on Apr 10, 2008 09:02 PM

As far as I can tell Ruby doesn't let you reassign functions (ie. Func1 = Func2) but after much experimentation I've found some possible workarounds.

Using Object.send and Symbols:

# Variables can store symbols like strings.
@func_symb = :side_1

# A convienence function
def decide
  Object.send(@func_symb)
end

def side_1
  p "Bacon"
  @func_symb = :side_2
end

def side_2
  p "Eggs"
  @func_symb = :side_1
end

# Now, when we call func the first time it will then call "side_1"
>>> decide
"Bacon"

# If we call it a second time, it calls "side_2"
>>> decide
"Eggs"

This method is a more natural way of doing things because it allows you to call decide like a normal function, however, passing arguments is a little less flexible.

Using Procs:

# This instance variable is what is called.
# Note: I use ``Proc.new`` because it throws away any
# extra variables passed to it instead of throwing an error.
# If you'd rather it throw errors you can use ``proc {}``
@decide = Proc.new {side_1}

def side_1
  p "Bacon"
  @decide = Proc.new {side_2}
end

def side_2
  p "Eggs"
  @decide = Proc.new {side_1}
end

# Calling a Proc is a bit different than a typical function.
>>> @decide[]
"Bacon"

# You may also call it like this
>>> @decide.call()
"Eggs"

I personally prefer this method as it gives you a bit more flexability with arguments and means you don't need to define a function for every call. (Ie. You can make a function call once then get disabled by adding @decide = Proc.new {return false})

Disclaimer:

I'm not a Ruby expert, so I can't say how reliable either of these methods will be,
or if one is inherently better than the other (I would vote the first because of its use of symbols).
dynamicfunctionruby
RSS