不使用字符串文字时的字符串插值 [英] String interpolation when not using a string literal

查看:42
本文介绍了不使用字符串文字时的字符串插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Ruby script that used string interpolation to build error messages.

p "#{vName} is not a defined variable"  => 'xxx is not a defined variable'

另一位程序员试图将字符串文字具体化到一个单独的配置文件中.当然,他没有得到替补.

Another programmer came through and attempted to externalize the string literals to a separate configuration file. Of course, he doesn't get the substitution.

p err_string_from_config  => '#{vName} is not a defined variable'

我环顾四周,但想不出比转换为 sprintf 字符串并使用 printf 更好的方法.

I've looked around, but couldn't come up with anything better than converting to sprintf strings and using printf.

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

Does anybody know how to get the #{} substitution to work on strings that are not double quote literals within the Ruby script?

推荐答案

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

Actually Ruby has functionality very similar to John's Python example:

$ irb
>> greeting = 'hello %s, my name is %s!'
>> interpolated = greeting % ['Mike', 'John']
=> "hello Mike, my name is John!"
>>

如果您的参数是数组常量,这也很有用.如果您必须使用 #{} 样式插值,您可以使用 eval:

This is also useful if your argument is an array constant. If you must use #{} style interpolation you could use eval:

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

eval 方法将比使用 % 样式插值慢得多,因此需要权衡.

The eval approach is going to be much slower than using % style interpolation, so it's a trade-off.

这篇关于不使用字符串文字时的字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆