Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.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 不使用字符串文字时的字符串插值_Ruby - Fatal编程技术网

Ruby 不使用字符串文字时的字符串插值

Ruby 不使用字符串文字时的字符串插值,ruby,Ruby,我有一个Ruby脚本,它使用字符串插值来生成错误消息 p "#{vName} is not a defined variable" => 'xxx is not a defined variable' 另一个程序员过来,试图将字符串文本外部化到一个单独的配置文件中。当然,他没有得到替补 p err_string_from_config => '#{vName} is not a defined variable' 我环顾了四周,但是没有比转换成sprintf字符串和使用pri

我有一个Ruby脚本,它使用字符串插值来生成错误消息

p "#{vName} is not a defined variable"  => 'xxx is not a defined variable'
另一个程序员过来,试图将字符串文本外部化到一个单独的配置文件中。当然,他没有得到替补

p err_string_from_config  => '#{vName} is not a defined variable'
我环顾了四周,但是没有比转换成sprintf字符串和使用printf更好的方法了


有人知道如何使用{}替换来处理Ruby脚本中不是双引号文本的字符串吗?

实际上Ruby的功能与John的Python示例非常相似:

$ irb
>> greeting = 'hello %s, my name is %s!'
>> interpolated = greeting % ['Mike', 'John']
=> "hello Mike, my name is John!"
>>
如果参数是数组常量,这也很有用。如果必须使用#{}样式的插值,则可以使用eval:

>> greeting = 'hi #{name}'    # notice name is not defined yet
>> name = "mike"
>> eval '"' + greeting + '"'

eval方法将比使用%样式插值慢得多,因此这是一种折衷办法。

以下是我的做法,仅供参考。更清楚一点

gief = '#{later} please'
later = "later"

puts eval(%Q["#{gief}"])
# => later please
但老实说,这真是一种恶作剧。除非您有很好的理由使用字符串,否则请改用proc。我总是尝试使用纯ruby而不是求值字符串

gief = Proc.new {|l| "#{l} please" }
later = "later"

puts gief.call(later)
# => later please

我建议您看看哪个提供了更强大的功能(例如,您可以按名称引用参数)。 前面的示例如下所示:

greeting = Liquid::Template.parse("hello {{your_name}}, my name is {{my_name}}!")
interpolated = greeting.render('your_name' => 'Mike', 'my_name' => 'John')
# => "hello Mike, my name is John!"

是的,我希望找到一种不需要他修改字符串的方法。这没什么大不了的,但在他问起这件事之后,我不得不看看是否有办法让#{}替换在不使用文本字符串的情况下工作。似乎应该有办法。@John:如果我每犯一个小错误都有一美元,那没问题。。。(实际上我也不知道Python会这么做);)@迈克:我更新了我的答案,提供了关于如何使用{}式插值的信息。谢谢,我没有想到使用eval和包装双引号的技巧。谢谢,很高兴知道。这比我认为我们想要添加到一个非常简单的脚本中的内容要多一些(老实说,我不确定他们为什么觉得有必要将字符串外部化)。是的,我当然倾向于同意使用eval是我倾向于避免的事情。如果这是需要错误策略的更大“系统”的一部分,我可能会使用模板解决方案,或者将每条消息转换为Proc(顺便说一下,有趣的解决方案)。我们可能会使用eval。