Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么使用ruby eval执行包含函数调用的字符串失败_Ruby - Fatal编程技术网

为什么使用ruby eval执行包含函数调用的字符串失败

为什么使用ruby eval执行包含函数调用的字符串失败,ruby,Ruby,我对Ruby很陌生,所以我希望这个问题在其他地方没有得到回答。但我已经在这里和互联网上搜索了很长一段时间,还没有结果 我正在从一个文本文件中读取一组文件路径。每个文件路径都有一些表达式(即#{…})嵌入到字符串中。例如: input = 'E:/files/storage/#{high_or_low}/#{left_or_right}/*.dll' def high_or_low 'low' end def left_or_right 'left' end # It rep

我对Ruby很陌生,所以我希望这个问题在其他地方没有得到回答。但我已经在这里和互联网上搜索了很长一段时间,还没有结果

我正在从一个文本文件中读取一组文件路径。每个文件路径都有一些表达式(即#{…})嵌入到字符串中。例如:

input = 'E:/files/storage/#{high_or_low}/#{left_or_right}/*.dll'
def high_or_low
    'low'
end

def left_or_right
    'left'
end

# It represents a file path on the disk drive
input = 'E:/files/storage/#{high_or_low}/#{left_or_right}/*.dll'
puts input

# Now how do I execute this 'input' string so that it behaves as if it was defined with quotes?
result = eval input
puts result
无论如何,我想把这些字符串当作ruby代码来计算,并替换这些表达式。例如:

input = 'E:/files/storage/#{high_or_low}/#{left_or_right}/*.dll'
def high_or_low
    'low'
end

def left_or_right
    'left'
end

# It represents a file path on the disk drive
input = 'E:/files/storage/#{high_or_low}/#{left_or_right}/*.dll'
puts input

# Now how do I execute this 'input' string so that it behaves as if it was defined with quotes?
result = eval input
puts result
我特意在原始输入字符串周围加上单引号,以表明当字符串从磁盘输入时,嵌入在字符串中的表达式是未计算的。那么如何用这些表达式计算字符串呢?如上所示使用eval似乎不起作用。我得到这个错误:

test_eval.rb:15: compile error (SyntaxError)
test_eval.rb:15: syntax error, unexpected tIDENTIFIER, expecting $end

谢谢

pst向您指出了它失败的原因。另一种选择是,根据您的数据外观,这可能有效,也可能无效。。。但是如果它是带有方法名的简单字符串(特别是不包含嵌套的“}”


啊,找到了。pst让我朝着正确的方向开始了。 因此,一旦我将输入变量用引号括起来,它就起作用了:

result = eval '"' + input + '"'
puts result

=>E:/files/storage/low/left/*.dll

语法错误与字符串插值中的方法调用无关。减少测试用例并以更有用的方式显示结果(例如,仅
放置
)。尝试运行此“语句”在IRB中:
E:/files/storage/low/high/*.dll
并比较结果。不管怎样,一旦消除了这条红鲱鱼..当字符串插值发生时,它就可以清晰地看到,这是在评估文本的时候。如果您确实想使用icky
eval
hack,请再次与我建议在IRB中运行的行进行比较。确定吗,我在irb中输入了那个表达式,我看到了语法错误。看起来字符串被执行时好像它不是一个字符串。我仍然不知道如何解决这个问题…有没有替代eval的方法?啊,找到了…eval''+input+'”'我尝试了这个方法,神奇而神秘地成功了,但我确实得到了这个警告:test_eval.rb:16:warning:regexp的间隔测试无效。\u eval.rb:16:warning:regexp有`}'而没有转义。'在这个regexp中,就像我在#中做的一样。我没有得到那个警告,但可能是由于不同的Ruby版本。它通过将匹配传递给块(s将是“#{string}”来工作.1被设置为regexp中的捕获。然后我们调用send在当前范围内调用该方法。不知道为什么有人对此进行了否决?这非常有效,而且是一个非常简单的答案。