我正在寻找一种在Ruby中连接字符串的更优雅的方式。

我有如下一行:

source = "#{ROOT_DIR}/" << project << "/App.config"

有更好的方法吗?

那么<<和+之间有什么区别呢?


当前回答

您可以使用+或<<操作符,但在ruby中.concat函数是最可取的,因为它比其他操作符快得多。你可以用它。

source = "#{ROOT_DIR}/".concat(project.concat("/App.config"))

其他回答

因为这是一个路径,我可能会使用数组和join:

source = [ROOT_DIR, project, 'App.config'] * '/'

你说的是串联?那么#concat方法呢?

a = 'foo'
a.object_id #=> some number
a.concat 'bar' #=> foobar
a.object_id #=> same as before -- string a remains the same object

公平地说,concat别名为<<。

情况很重要,例如:

# 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

在第一个示例中,与+操作符连接将不会更新输出对象,然而,在第二个示例中,<<操作符将在每次迭代中更新输出对象。因此,对于上述类型的情况,<<更好。

你可以通过以下几种方式做到这一点:

正如你用<<所示,但这不是通常的方式 用字符串插值 source = "#{ROOT_DIR}/#{项目}/App.config" 与+ source = "#{ROOT_DIR}/" + project + "/App.config"

据我所见,第二种方法在内存/速度方面似乎更有效(虽然没有测量过)。当ROOT_DIR为nil时,这三个方法都会抛出一个未初始化的常量错误。

在处理路径名时,您可能希望使用File。连接以避免混淆路径名分隔符。

说到底,这是一个品味问题。

+操作符是正常的连接选择,并且可能是连接字符串的最快方式。

+和<<之间的区别在于<<改变了对象的左侧,而+则不会。

irb(main):001:0> s = 'a'
=> "a"
irb(main):002:0> s + 'b'
=> "ab"
irb(main):003:0> s
=> "a"
irb(main):004:0> s << 'b'
=> "ab"
irb(main):005:0> s
=> "ab"