'xxx is not a defined variab-6ren">
gpt4 book ai didi

ruby - 不使用字符串文字时的字符串插值

转载 作者:数据小太阳 更新时间:2023-10-29 06:37:47 25 4
gpt4 key购买 nike

我有一个使用字符串插值来构建错误消息的 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 方法将比使用 % 样式插值慢得多,因此这是一个权衡。

关于ruby - 不使用字符串文字时的字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/646126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com