Ruby循环遍历数组中的每个元素n次
我很难找到一个确切的例子 如果我有一个包含5个元素的数组。例如Ruby循环遍历数组中的每个元素n次,ruby,Ruby,我很难找到一个确切的例子 如果我有一个包含5个元素的数组。例如 list = [5, 8, 10, 11, 15] 如果要循环,我想获取该数组的第8个(例如)元素。我不想复制数组并获取第8个元素,因为第n个元素可能会更改 基本上,第8个元素应该是数字10 有什么干净的方法可以做到这一点吗?用数学来解救 list[(8 % list.length) - 1] 关于这个我们喜爱的模算子,数学拯救了它 list[(8 % list.length) - 1] 关于我们喜欢的模运算符,这应该是: d
list = [5, 8, 10, 11, 15]
如果要循环,我想获取该数组的第8个(例如)元素。我不想复制数组并获取第8个元素,因为第n个元素可能会更改
基本上,第8个元素应该是数字10
有什么干净的方法可以做到这一点吗?用数学来解救
list[(8 % list.length) - 1]
关于这个我们喜爱的模算子,数学拯救了它
list[(8 % list.length) - 1]
关于我们喜欢的模运算符,这应该是:
def fetch_cycled_at_position(ary, num)
ary[(num % ary.length) - 1]
end
ary = _
=> [5, 8, 10, 11, 15]
fetch_cycled_at_position(ary, 1) # Fetch first element
=> 5
fetch_cycled_at_position(ary, 5) # Fetch 5th element
=> 15
fetch_cycled_at_position(ary, 8) # Fetch 8th element
=> 10
这应该做到:
def fetch_cycled_at_position(ary, num)
ary[(num % ary.length) - 1]
end
ary = _
=> [5, 8, 10, 11, 15]
fetch_cycled_at_position(ary, 1) # Fetch first element
=> 5
fetch_cycled_at_position(ary, 5) # Fetch 5th element
=> 15
fetch_cycled_at_position(ary, 8) # Fetch 8th element
=> 10
出于好奇,使用:
这是非常低效的,但很花哨。只是出于好奇,使用:
这是非常低效的,但是很花哨。我在irb中运行了这些来获得输出
irb(main):006:0> list = [5, 8, 10, 11, 15]
=> [5, 8, 10, 11, 15]
irb(main):007:0> list[(8 % list.length) - 1]
=> 10
希望它能对您有所帮助。我在irb中运行了这些以获得输出
irb(main):006:0> list = [5, 8, 10, 11, 15]
=> [5, 8, 10, 11, 15]
irb(main):007:0> list[(8 % list.length) - 1]
=> 10
希望它能帮助您。您可以使用:
它是7
,因为数组是基于零的。您可以使用:
这是
7
,因为数组是零基的。我需要的数学!非常感谢。我的荣幸先生:)我需要的数学!非常感谢。不客气,先生:)