=和<<之间的Ruby差异以连接字符串

前端之家收集整理的这篇文章主要介绍了=和<<之间的Ruby差异以连接字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?7个
在Ruby 1.8.7上,当发现<<<<<<<<<<<<<<<<<<和=在String对象上:
y = ""
 start = Time.now
 99999.times { |x| y += "some new string"  }
 puts "Time: #{Time.now - start}"
 # Time: 31.56718

 y=''
 start = Time.now
 99999.times { |x| y << "some new string"  }
 puts "Time: #{Time.now - start}"
 # Time: 0.018256

我谷歌了解一下,发现了一些结果:

http://www.rubylove.info/post/1038516765/difference-between-string-concatenation-ruby-rails

说<<<修改两个字符串,而=仅修改调用者.我不明白为什么然后<<快点. 接下来我去了Ruby doc,但我想知道为什么没有方法= http://ruby-doc.org/core-2.2.0/String.html

解决方法

挖掘机运算符<<因为铲子操作符允许修改原始字符串,所以在处理长字符串时执行要好得多,而每次运行时,=必须将第一个字符串中的所有文本复制到新字符串中. String类上没有定义=运算符,因为=是组合运算符.简而言之,x =“asdf”完全等同于x = x“asdf”,因此您应该在字符串类上引用运算符,而不是查找a =运算符.
原文链接:https://www.f2er.com/ruby/264747.html

猜你在找的Ruby相关文章