Arrays Ruby按索引选择
我正在尝试从数组中选择元素:Arrays Ruby按索引选择,arrays,ruby,Arrays,Ruby,我正在尝试从数组中选择元素: arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'] 其索引是斐波那契数。我想要结果: ['a', 'b', 'c', 'd', 'f', 'i', 'n'] 我的代码返回元素和索引 def is_fibonacci?(i, x = 1, y = 0) return true if i == x || i == 0 return false if x &g
arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
其索引是斐波那契数。我想要结果:
['a', 'b', 'c', 'd', 'f', 'i', 'n']
我的代码返回元素和索引
def is_fibonacci?(i, x = 1, y = 0)
return true if i == x || i == 0
return false if x > i
is_fibonacci?(i, x + y, x)
end
arr.each_with_index.select do |val, index|
is_fibonacci?(index)
end
此代码返回:
[["a", 0], ["b", 1], ["c", 2], ["d", 3], ["f", 5], ["i", 8], ["n", 13]]
请帮助我理解我如何仍然可以遍历数组并计算索引,但只返回元素。到目前为止,您的代码看起来很棒,我不会更改它。您可以在事后检查您的结果,并将[element,index]对更改为仅包含元素,方法是对每一对进行检查,并仅取以下值:
您可以将代码的最后一位更改为
arr.select.with_index do |val, index|
is_fibonacci?(index)
end
这是因为如果在没有块的情况下调用select等方法,就会得到一个对象,然后可以在该对象上链接更多可枚举的方法
在本例中,我使用了with_index,这与在原始数组上使用_index调用每个_非常相似。但是,由于这发生在select之后而不是之前,select将返回原始数组中的项,而不附加索引。下面是另一种方法
index_gen = Enumerator.new do |y|
i = 0
j = 1
loop do
y.yield i unless i==j
i, j = j, i + j
end
end
#=> #<Enumerator: #<Enumerator::Generator:0x007fa3eb979028>:each>
arr.values_at(*index_gen.take_while { |n| n < arr.size })
#=> ["a", "b", "c", "d", "f", "i", "n"]
或
注:
我假设斐波那契数从零开始,而不是从一开始,这是现代的定义。
斐波那契序列从0,1,1,2,。。。。枚举器索引的构造跳过了第二个1。
当{n{n这正是我想要的。我仍然想使用。选择。非常感谢!
index_gen = Enumerator.new do |y|
i = 0
j = 1
loop do
y.yield i unless i==j
i, j = j, i + j
end
end
#=> #<Enumerator: #<Enumerator::Generator:0x007fa3eb979028>:each>
arr.values_at(*index_gen.take_while { |n| n < arr.size })
#=> ["a", "b", "c", "d", "f", "i", "n"]
index_gen.take_while { |n| n < arr.size }.map { |n| arr[n] }
#=> ["a", "b", "c", "d", "f", "i", "n"]