我正在寻找一种在Ruby中连接字符串的更优雅的方式。
我有如下一行:
source = "#{ROOT_DIR}/" << project << "/App.config"
有更好的方法吗?
那么<<和+之间有什么区别呢?
我正在寻找一种在Ruby中连接字符串的更优雅的方式。
我有如下一行:
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别名为<<。
其他回答
你说的是串联?那么#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别名为<<。
+操作符是正常的连接选择,并且可能是连接字符串的最快方式。
+和<<之间的区别在于<<改变了对象的左侧,而+则不会。
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"
从http://greyblake.com/blog/2012/09/02/ruby-perfomance-tricks/
使用<<即concat比+=更有效,因为后者创建了一个临时对象并用新对象覆盖第一个对象。
require 'benchmark'
N = 1000
BASIC_LENGTH = 10
5.times do |factor|
length = BASIC_LENGTH * (10 ** factor)
puts "_" * 60 + "\nLENGTH: #{length}"
Benchmark.bm(10, '+= VS <<') do |x|
concat_report = x.report("+=") do
str1 = ""
str2 = "s" * length
N.times { str1 += str2 }
end
modify_report = x.report("<<") do
str1 = "s"
str2 = "s" * length
N.times { str1 << str2 }
end
[concat_report / modify_report]
end
end
输出:
____________________________________________________________
LENGTH: 10
user system total real
+= 0.000000 0.000000 0.000000 ( 0.004671)
<< 0.000000 0.000000 0.000000 ( 0.000176)
+= VS << NaN NaN NaN ( 26.508796)
____________________________________________________________
LENGTH: 100
user system total real
+= 0.020000 0.000000 0.020000 ( 0.022995)
<< 0.000000 0.000000 0.000000 ( 0.000226)
+= VS << Inf NaN NaN (101.845829)
____________________________________________________________
LENGTH: 1000
user system total real
+= 0.270000 0.120000 0.390000 ( 0.390888)
<< 0.000000 0.000000 0.000000 ( 0.001730)
+= VS << Inf Inf NaN (225.920077)
____________________________________________________________
LENGTH: 10000
user system total real
+= 3.660000 1.570000 5.230000 ( 5.233861)
<< 0.000000 0.010000 0.010000 ( 0.015099)
+= VS << Inf 157.000000 NaN (346.629692)
____________________________________________________________
LENGTH: 100000
user system total real
+= 31.270000 16.990000 48.260000 ( 48.328511)
<< 0.050000 0.050000 0.100000 ( 0.105993)
+= VS << 625.400000 339.800000 NaN (455.961373)
我更喜欢使用Pathname:
require 'pathname' # pathname is in stdlib
Pathname(ROOT_DIR) + project + 'App.config'
关于ruby文档中的<<和+:
+:返回一个包含连接到str的other_str的新String
<<:将给定对象连接到str。如果对象是0到255之间的Fixnum,则将其转换为连接前的字符。
因此,区别在于第一个操作数变成了什么(<<在适当的位置进行更改,+返回新字符串,因此内存更重),如果第一个操作数是Fixnum(<<将添加,就像它是代码等于该数字的字符,+将引发错误)
这里有更多的方法:
"String1" + "String2"
"#{String1} #{String2}"
String1<<String2
等等……