gpt4 book ai didi

ruby - 使用首选默认值扩展数组

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:24 25 4
gpt4 key购买 nike

Array#[]= 的文档注意到

If indices are greater than the current capacity of the array, the array grows automatically.

当它自动增长时,它会使用 nil 值:

arr = []
arr[2] = "!"
arr # => [nil, nil, "!"]

是否可以指定前两个值的默认值?

目前,我在做

arr = []
index = 2
currently_uninitialized_value_range = (arr.length)...(index)
default_values = currently_uninitialized_value_range.map{ "" }
arr[currently_uninitialized_value_range] = default_values
arr[index] = "!"
arr # => ["", "", "!"]

这有点冗长。

我使用的是数组而不是散列,因为它们代表我将要输入到电子表格中的值,而我使用的库 (Axlsx) 更喜欢按行添加数据行。

最佳答案

Array#fill可能是你的门票。

arr = []

index = 2
arr.fill( "", arr.length...index )
arr[index] = "!"
# => ["", "", "!"]

index = 5
arr.fill( "", arr.length...index )
arr[index] = "!"
# => ["", "", "!", "", "", "!"]

index = 1
arr.fill( "", arr.length...index )
arr[index] = "!"
#=> ["", "!", "!", "", "", "!"]

关于ruby - 使用首选默认值扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com