在不使用eval的情况下在Ruby中执行比较

时间:2015-11-19 21:16:54

标签: ruby ruby-on-rails-4 eval

["if", "2", "<", "4"]

如何在不使用.eval()的情况下将这些字符串组合在一起并计算它们是否真实?

为了澄清,上面只是一个数组,我需要操纵内容以便评估if 2 < 4,它应该返回true

1 个答案:

答案 0 :(得分:0)

您可以尝试使用它来解析语句并将它们组合成更复杂的语句。

def bool_parse(statement)
  op, left, method, right = statement
  left = left.to_i unless left["\'"]
  right = right.to_i unless right["\'"]

  case op
  when "if", "elsif"
    left.send(method, right)
  when "unless"
    !left.send(method, right)
  end
end

def compose(statements)
  correct = statements.detect do |s, v|
    bool_parse(s)
  end
  correct && correct.last
end

compose({["if", "3", ">", "5"] => 1})
#=> nil
compose({["if", "3", ">", "5"] => 1, ["elsif", "2", ">", "-1"] => 2})
#=> 2
相关问题