Ruby 中的字符串连接 [英] String concatenation in Ruby
问题描述
我正在寻找一种在 Ruby 中连接字符串的更优雅的方法.
I am looking for a more elegant way of concatenating strings in Ruby.
我有以下几行:
source = "#{ROOT_DIR}/" << project << "/App.config"
有没有更好的方法来做到这一点?
Is there a nicer way of doing this?
那么,<<
和 +
之间有什么区别?
And for that matter what is the difference between <<
and +
?
推荐答案
您可以通过多种方式做到这一点:
You can do that in several ways:
- 正如你用
<<
展示的那样,但这不是通常的方式 带字符串插值
- As you shown with
<<
but that is not the usual way With string interpolation
source = "#{ROOT_DIR}/#{project}/App.config"
与 +
source = "#{ROOT_DIR}/" + project + "/App.config"
从我所看到的(虽然没有测量),第二种方法在内存/速度方面似乎更有效.当 ROOT_DIR 为 nil 时,这三种方法都会抛出未初始化的常量错误.
The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.
在处理路径名时,您可能需要使用 File.join
以避免弄乱路径名分隔符.
When dealing with pathnames, you may want to use File.join
to avoid messing up with pathname separator.
归根结底,这是一个品味问题.
In the end, it is a matter of taste.
这篇关于Ruby 中的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!