分配给数组并替换出现的 nil 值
问候!
当如下所示为数组赋值时,如何用 0
替换 nil
?
array = [1,2,3]
array[10] = 2
array # => [1, 2, 3, nil, nil, nil, nil, nil, nil, nil, 2]
如果在分配时不可能,那么之后我该怎么做才是最好的?我想到了 array.map { |e| e.nil? ? 0 : e },但是……
谢谢!
Greetings!
When assigning a value to an array as in the following, how could I replace the nil
s by 0
?
array = [1,2,3]
array[10] = 2
array # => [1, 2, 3, nil, nil, nil, nil, nil, nil, nil, 2]
If not possible when assigning, how would I do it the best way afterwards? I thought of array.map { |e| e.nil? ? 0 : e }
, but well…
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要在分配后更改数组:
请注意,这也会将
false
转换为0
。如果你想在赋值期间使用零,那就有点混乱了:
To change the array after assignment:
Note that this also converts
false
to0
.If you want to use zeros during assignment, it's a little messy:
没有内置函数可以替换数组中的
nil
,所以,是的,map
是正确的选择。如果较短的版本会让您更快乐,您可以这样做:There is no built-in function to replace
nil
in an array, so yes,map
is the way to go. If a shorter version would make you happier, you could do:nil.to_i 是 0,如果所有数字都是整数,那么下面应该可以工作。我认为这也是这里最短的答案。
nil.to_i is 0, if all the numbers are integers then below should work. I think It is also the shortest answer here.
就地更改数组
如果数组可以包含
false
,则需要使用它To change the array in place
If the array can contain
false
you'll need to use this instead这个答案太短了,所以我再补充几句话。
This answer is too short so I am adding a few more words.
另一种方法是定义您自己的函数来向数组添加值。
Another approach would be to define your own function for adding a value to the array.