为什么String.tap不返回修改后的字符串?

the*_*ing 2 ruby

我正在做

String.new.tap do |string|
  polygon.points.each do |point|
    x, y = point.x + (page_padding/2), point.y + (page_padding/2)
    string += "#{x}, #{y} "
  end
end
Run Code Online (Sandbox Code Playgroud)

但它返回一个空字符串.

如果我打电话

Array.new.tap do |array|
  polygon.points.each do |point|
    x, y = point.x + (page_padding/2), point.y + (page_padding/2)
    array << "#{x}, #{y} "
  end
end
Run Code Online (Sandbox Code Playgroud)

它返回一个修改过的数组.为什么这不适用于字符串?

使用Ruby 2.4.0

Ily*_*lya 5

+=不是mutator:str1 += str2创建一个新字符串.使用<<变异字符串:

string1 = 'foo'
string1.object_id
=> 70298699576220
(string1 += '2').object_id # changed
=> 70298695972240
(string1 << '2').object_id # not changed: original object has been mutated
=> 70298695972240
Run Code Online (Sandbox Code Playgroud)

tap只是将自己产生于块,然后返回self.由于self您的实例不会更改,因此只需返回原始值即可.

  • 拼写出来:`str1 + = str2`创建一个__new__字符串.:) (2认同)