加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby运算符与铲子混淆(<<)和=,Concating数组

发布时间:2020-12-17 02:49:23 所属栏目:百科 来源:网络整理
导读:我已经读过 =.但我想我可能无法理解这些差异,因为我的预期代码不会输出我想要实现的内容. 回应 Ruby differences between += and to concatenate a string 我想把“猫”解读成一个字母/单词的数组 = [“c”,“ca”,“cat”,“a”,“at”,“t”] def helper(w
我已经读过<<<<<<< =.但我想我可能无法理解这些差异,因为我的预期代码不会输出我想要实现的内容. 回应 Ruby differences between += and << to concatenate a string

我想把“猫”解读成一个字母/单词的数组
=> [“c”,“ca”,“cat”,“a”,“at”,“t”]

def helper(word)
words_array = []
idx = 0
while idx < word.length 
    j = idx  
    temp = ""
    while j < word.length
        **temp << word[j]**
        words_array << temp unless words_array.include?(temp) 
    j += 1 
    end
    idx += 1 
end 
p words_array
end
helper("cat")

我不明白为什么
温度<<字[j]的
与temp = word [j]不同,对我而言,我在这个特定情况下的逻辑是正确的.

解决方法

一个区别是因为<<在适当的地方工作它比=快一些.以下代码

require 'benchmark'

a = ''
b= ''

puts Benchmark.measure {
  100000.times { a << 'test' }
}

puts Benchmark.measure {
  100000.times { b += 'test' }
}

产量

更新

我原本误解了这个问题.这是最近发生的事情. Ruby变量只存储对象的引用,而不是对象本身.这里的简化代码与您的代码完全相同,并且具有相同的问题.我告诉它在循环的每次迭代中打印temp和words_array.


这是它打印的内容:


正如您所看到的,在内部循环的第一次迭代之后,ruby只是替换words_array的最后一个元素.这是因为words_array持有对temp引用的字符串对象的引用,并且<<修改该对象而不是创建新对象. 在外循环的每次迭代中,temp被设置为一个新对象,并且该新对象被附加到words_array,因此它不会替换先前的元素. =构造在内循环的每次迭代中向temp返回一个新对象,这就是它的行为与预期一致的原因.

0.000000 0.000000 0.000000 ( 0.004653) 0.
require 'benchmark'

a = ''
b= ''

puts Benchmark.measure {
  100000.times { a << 'test' }
}

puts Benchmark.measure {
  100000.times { b += 'test' }
}

0 0.

require 'benchmark'

a = ''
b= ''

puts Benchmark.measure {
  100000.times { a << 'test' }
}

puts Benchmark.measure {
  100000.times { b += 'test' }
}
require 'benchmark' a = '' b= '' puts Benchmark.measure { 100000.times { a << 'test' } } puts Benchmark.measure { 100000.times { b += 'test' } }require 'benchmark' a = '' b= '' puts Benchmark.measure { 100000.times { a << 'test' } } puts Benchmark.measure { 100000.times { b += 'test' } }0 0.120000 ( 0.108534)
def helper(word) words_array = [] word.length.times do |i| temp = '' (i...word.length).each do |j| temp << word[j] puts "temp:t#{temp}" words_array << temp unless words_array.include?(temp) puts "words:t#{words_array}" end end words_array end p helper("cat")temp: c words: ["c"] temp: ca words: ["ca"] temp: cat words: ["cat"] temp: a words: ["cat","a"] temp: at words: ["cat","at"] temp: t words: ["cat","at","t"] ["cat","t"]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读