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

标签 ruby operators concatenation

我读过<< += 之间的一些区别。但我想我可能不理解这些差异,因为我预期的代码没有输出我想要实现的。

回应Ruby differences between += and << to concatenate a string

我想将“Cat”解读为它的字母/单词数组 => ["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' }
}

产量

0.000000   0.000000   0.000000 (  0.004653)
0.060000   0.060000   0.120000 (  0.108534)

更新

我最初误解了这个问题。这是怎么回事。 Ruby 变量只存储对对象的引用,而不是对象本身。这是简化的代码,它与您的代码做同样的事情,并且有同样的问题。我告诉它打印 tempwords_array在循环的每次迭代中。

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", "at", "t"]

如您所见,在第一次内循环之后的每次迭代中,ruby 只是简单地替换了 words_array 的最后一个元素。 .那是因为 words_array持有对 temp 引用的字符串对象的引用, 和 <<就地修改该对象,而不是创建新对象。

在外循环的每次迭代中 temp设置为一个新对象,并且该新对象附加到 words_array , 所以它不会替换之前的元素。

+=构造返回一个新对象给temp在内循环的每次迭代中,这就是它按预期运行的原因。

关于ruby 运算符与铲子 (<<) 和 += 混淆,连接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38018895/

相关文章:

ruby-on-rails - Ruby on Rails 中的缩小和放大

java - 代码如何工作 - 应用于样式时为 "SWT.MULTI | SWT.SINGLE"

c - if 语句中的简单 "not equal"运算符未按预期工作

python - 连接单列多个不同形状的文件

python - numpy.concatenate float64(101,1) 和 float64(101,)

ruby-on-rails - 未定义的方法 `stringify_keys' 为 "create":String in ruby on rails again

ruby - 计算 ruby 的百分比?

java - 连接 cucumber 检查java中的场景失败

C++:是否可以重载 |位于同一类中的两个不同枚举的运算符?

mysql - 将数组值写入 "SELECT ...."