Ruby:如何通过对象引用调用函数?

Kyl*_*tan 1 ruby idioms method-dispatch

考虑这个人为的例子:

# Dispatch on value of fruit_kind:

TYPE_A = :apple
TYPE_B = :banana
TYPE_C = :cherry

eating_method = nil

case fruit_kind
  # Methods to use for different kinds of fruit (assume these are
  #  already defined)
  when TYPE_A then eating_method = bite
  when TYPE_B then eating_method = peel
  when TYPE_C then eating_method = om_nom_nom
end
Run Code Online (Sandbox Code Playgroud)

现在我想eating_method用一些参数来调用目标:

# Doesn't work; this tries to invoke a method called "eating_method",
# not the reference I defined earlier.
eating_method(some_fruit)
Run Code Online (Sandbox Code Playgroud)

在Ruby中这样做的正确方法是什么?

Pes*_*sto 6

使用send.发送采用函数名称,因此使用符号:

case fruit_kind
  # Methods to use for different kinds of fruit (assume these are
  #  already defined)
  when TYPE_A then eating_method = :bite
  when TYPE_B then eating_method = :peel
  when TYPE_C then eating_method = :om_nom_nom
end

send(eating_method, some_fruit)
Run Code Online (Sandbox Code Playgroud)

编辑:

顺便说一下,你是否知道你可以case通过做这样的事情来让它变得更漂亮:

eating_method = case fruit_kind
  # Methods to use for different kinds of fruit (assume these are
  #  already defined)
  when TYPE_A then :bite
  when TYPE_B then :peel
  when TYPE_C then :om_nom_nom
  else nil
end
Run Code Online (Sandbox Code Playgroud)

或者,正如Sii所提到的,使用哈希代替:

fruit_methods = {:apple => :bite, :banana => :peel, :cherry => :om_nom_nom}
send(fruit_methods[fruit_kind], some_fruit)    
Run Code Online (Sandbox Code Playgroud)