gpt4 book ai didi

ruby - block 数组的整数

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

我需要将整数转换为间隔数组。例如,

number_to_steps(number: 10, step: 3)
# => [[0, 2], [3, 5], [6, 8], [9, 9]]

number_to_steps(number: 7, step: 2)
# => [[0, 1], [2, 3], [4, 5], [6, 6]]

number_to_steps(number: 8, step: 2)
# => [[0, 1], [2, 3], [4, 5], [6, 7]]

我试过:

def number_to_ranges(number:, size:)
chunks = ((number - 1) / size.to_f).ceil

(0..chunks - 1).map do |index|
from = index * size
to = (index + 1) * size - 1

[ from, to > number ? number : to ]
end
end

但它不能正常工作。例如,

number_to_ranges(number: 14, step: 4)
[[0, 3], [4, 7], [8, 11], [12, 14]]

不应转到 14。

有什么想法吗?

最佳答案

(您的方法的)替代方法是使用 each_slice .

def number_to_steps(number:, step:)
(0...number).each_slice(step).map { |arr| [arr.first, arr.last] }
end

测试:

number_to_steps(number: 10, step: 3)
#=> [[0, 2], [3, 5], [6, 8], [9, 9]]

number_to_steps(number: 7, step: 2)
#=> [[0, 1], [2, 3], [4, 5], [6, 6]]

number_to_steps(number: 8, step: 2)
#=> [[0, 1], [2, 3], [4, 5], [6, 7]]

关于ruby - block 数组的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51665814/

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