我正在寻找一种在Ruby中连接字符串的更优雅的方式。
我有如下一行:
source = "#{ROOT_DIR}/" << project << "/App.config"
有更好的方法吗?
那么<<和+之间有什么区别呢?
我正在寻找一种在Ruby中连接字符串的更优雅的方式。
我有如下一行:
source = "#{ROOT_DIR}/" << project << "/App.config"
有更好的方法吗?
那么<<和+之间有什么区别呢?
当前回答
情况很重要,例如:
# 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
在第一个示例中,与+操作符连接将不会更新输出对象,然而,在第二个示例中,<<操作符将在每次迭代中更新输出对象。因此,对于上述类型的情况,<<更好。
其他回答
如果只是连接路径,可以使用Ruby自己的File。连接方法。
source = File.join(ROOT_DIR, project, 'App.config')
情况很重要,例如:
# 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
在第一个示例中,与+操作符连接将不会更新输出对象,然而,在第二个示例中,<<操作符将在每次迭代中更新输出对象。因此,对于上述类型的情况,<<更好。
对于你的特殊情况,你也可以使用array# join构造文件路径类型的字符串:
string = [ROOT_DIR, project, 'App.config'].join('/')]
这有一个令人愉快的副作用,自动将不同类型转换为字符串:
['foo', :bar, 1].join('/')
=>"foo/bar/1"
这里有更多的方法:
"String1" + "String2"
"#{String1} #{String2}"
String1<<String2
等等……
你也可以这样使用%:
source = "#{ROOT_DIR}/%s/App.config" % project
这种方法也适用于'(单)引号。