Ruby块中的字符串连接

o2gm4chl  于 2023-04-05  发布在  Ruby
关注(0)|答案(1)|浏览(160)

我试图理解为什么相同的串联操作在正常上下文中构建字符串,但在each块中运行时构建数组。
例如,此串联按预期工作

irb(main):027:0> str = "test"
=> "test"
irb(main):028:0> str += "test"
=> "testtest"
irb(main):029:0> str += "test"
=> "testtesttest"

但是当在each块中迭代运行时,它会构建一个数组:

irb(main):030:0> str = ""
=> ""
irb(main):031:0> list = ["a", "b", "c"]
=> ["a", "b", "c"]
irb(main):032:1* list.each do |c|
irb(main):033:1*   str += c
irb(main):034:0> end
=> ["a", "b", "c"]
um6iljoc

um6iljoc1#

当提供块时,Array.each返回self(即list)。

irb(main):001:0> list = ["a", "b", "c"]
=> ["a", "b", "c"]
irb(main):002:0> list.each {}
=> ["a", "b", "c"]

之后检查str表明它确实被更改了。

irb(main):001:0> str = ""
=> ""
irb(main):002:0> list = ["a", "b", "c"]
=> ["a", "b", "c"]
irb(main):003:1* list.each do |c|
irb(main):004:1*   str += c
irb(main):005:0> end
=> ["a", "b", "c"]
irb(main):006:0> str
=> "abc"

相关问题