如何使用* args和& block传递Ruby方法的值?

时间:2016-04-14 21:04:26

标签: ruby

方法aasm定义为:

def aasm(*args, &block)
  if args[0].is_a?(Symbol) || args[0].is_a?(String)
    # using custom name
    state_machine_name = args[0].to_sym
    options = args[1] || {}
  else
    # using the default state_machine_name
    state_machine_name = :default
    options = args[0] || {}
  end
  .......
  #do something else
end

现在我们需要将整个aasm....放在一个字符串中并对其进行eval

  eval("aasm(:test) :column => 'col_name' {#{def_string}}")

  def_string = "state :fresh, :initial => true
                state :move
                event :submit do
                  transitions :from => :fresh, :to => :move
                end"     

unexpected ':', expecting end-of-input存在语法错误。我们尝试将(:test) :column => 'col_name'放入{}[],但错误并未消失。在一行中将所有值传递给aasm的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

你可能需要这样写:

eval("aasm(:test, :column => 'col_name') {#{def_string}}")