繁体   English   中英

将字符串转换为 Ruby 中的条件

[英]Converting a string to a condition in Ruby

我实际上有一个名为“cond”的字符串。 这是该字符串的内容:

"20 < 50"

我想将它插入到这样的条件中:(示例)

if 20 < 50
return "Hello"

但是那个条件是一个字符串,所以我不能这样写:

if cond
return "Hello"

所以我想知道是否可以将字符串转换为条件以设置为“if”条件。 如果可能的话,我该怎么做?

谢谢你。

eval可能只是你的朋友:

>> eval('20 < 50')
=> true

但是, eval将执行其参数中的任意代码; 你应该确保你的cond不能包含任何对你的系统健康有害的东西!

使用 eval 的一种替代方法可能是编写一个评估器(或使用/修改现有的评估器,例如Sterling Camden 的这个)。

正如他的代码要求您编写 lt、gt、eq 等,而不是 <、>、==、...。 正如 calc.rb 中的评论所述:

 # Equality and its clan (note we cannot use '==' or other two-character # non-word operators, because of the way we parse the string. Non-word # characters come in one at a time.

如果您知道条件将始终像您提供的示例一样基本,您可以这样做:

left, op, right = "20 < 50".split
cond = left.to_i.send(op.to_sym, right.to_i)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM