我正在寻找一种更优雅的方法来在Ruby中连接字符串。
我有以下代码行:
source = "#{ROOT_DIR}/" << project << "/App.config"
有没有更好的方法来做这件事?
此外,<<和+之间有什么区别?
我正在寻找一种更优雅的方法来在Ruby中连接字符串。
我有以下代码行:
source = "#{ROOT_DIR}/" << project << "/App.config"
有没有更好的方法来做这件事?
此外,<<和+之间有什么区别?
您可以使用+
或<<
运算符,但在Ruby中,.concat
函数是最可取的,因为它比其他运算符快得多。您可以像这样使用它。
source = "#{ROOT_DIR}/".concat(project.concat("/App.config"))
concat
后面多了一个 .
,是吗? - lacostenycoder%
:source = "#{ROOT_DIR}/%s/App.config" % project
'
。"最初的回答"您可以直接在字符串定义中进行拼接:
最初的回答
nombre_apellido = "#{customer['first_name']} #{customer['last_name']} #{order_id}"
情境很重要,例如:
# this will not work
output = ''
Users.all.each do |user|
output + "#{user.email}\n"
end
# the output will be ''
puts output
# this will do the job
output = ''
Users.all.each do |user|
output << "#{user.email}\n"
end
# will get the desired output
puts output
+
运算符进行字符串连接不会更新output
对象。然而,在第二个示例中,<<
运算符将在每次迭代中更新output
对象。因此,对于上述类型的情况,<<
更好。对于 Puppet:
$username = 'lala'
notify { "Hello ${username.capitalize}":
withpath => false,
}
对于您的特定情况,构建文件路径类型的字符串时,您还可以使用Array#join
:
string = [ROOT_DIR, project, 'App.config'].join('/')]
这个有一个愉快的副作用,可以自动将不同类型转换为字符串:
['foo', :bar, 1].join('/')
=>"foo/bar/1"