我不明白这段代码:
a = [ "a!", "b!", "c!", "d!" ]
a.collect!.with_index {|x, i| x[0...i]}
a #=> ["", "b", "c!", "d!"]
在 collect
行中,x[0...i]
做了什么?我看到了输出,但不明白它是如何做/得到它的。
最佳答案
根据docs :
Ranges constructed using .. run from the beginning to the end inclusively. Those created using ... exclude the end value..
所以 a..b
就像a <= x <= b
,而 a...b
就像a <= x < b
.即:
>> "a!"[0...0]
=> ""
>> "a!"[0...1]
=> "a"
>> "a!"[0...2]
=> "a!"
在你的a.collect!.with_index
, x
的值和 i
将是:
- “一个!” - 0 =>
"a!"[0...0]
=>""
- “啊!” - 1 =>
"b!"[0...1]
=>"b"
- “c!” - 2 =>
"c!"[0...2]
=>"c!"
- 等等...
关于 ruby x[0...i] 做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49221311/