ruby有eval吗

2024-09-28 15:14:59 发布

您现在位置:Python中文网/ 问答频道 /正文

鲁比有类似Python评估的东西吗?我在搜索谷歌,我不知道我是怎么搜索的,但我在上面找不到任何东西,也找不到如何使用它(如果有的话)

在python中,我想这样做

def doEval(object):
    return repr(eval(object))

上面的代码可以在python的idle或其他东西中执行并运行doEval('print(“hello”)')),它将打印“hello”,然后返回“None”来表示它已执行,在ruby中,我不介意它不做nil,但我希望它进行eval

在ruby里有这样的东西吗?谢谢。在


Tags: 代码nonehelloreturnobjectdefevalruby
2条回答

Googling "ruby eval" quickly reveals that the answer is yes.

eval(string [, binding [, filename [,lineno]]]) → obj

Evaluates the Ruby expression(s) in string. If binding is given, which must be a Binding object, the evaluation is performed in its context. If the optional filename and lineno parameters are present, they will be used when reporting syntax errors.

试试这个:

command = "puts 1"
eval(command)

http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-eval

相关问题 更多 >