Ruby 数组中每隔2项
我需要一个ruby公式来创建一个整数数组。数组必须每隔2个数字,如下所示Ruby 数组中每隔2项,ruby,Ruby,我需要一个ruby公式来创建一个整数数组。数组必须每隔2个数字,如下所示 [2, 3, 6, 7, 10, 11, 14, 15, 18, 19...] 我已经读了很多关于如何做其他数字或倍数的文章,但我不确定实现所需的最佳方法。此代码适用于任何起始数字到任何结束限制 i = 3 j = 19 x =[] (i...j).each do |y| x << y if (y-i)%4<2 end puts x 这应该可以以下是一种适用于任何阵列的方法 def every_o
[2, 3, 6, 7, 10, 11, 14, 15, 18, 19...]
我已经读了很多关于如何做其他数字或倍数的文章,但我不确定实现所需的最佳方法。此代码适用于任何起始数字到任何结束限制
i = 3
j = 19
x =[]
(i...j).each do |y|
x << y if (y-i)%4<2
end
puts x
这应该可以以下是一种适用于任何阵列的方法
def every_other_two arr
arr.select.with_index do |_, idx|
idx % 4 > 1
end
end
every_other_two((0...20).to_a) # => [2, 3, 6, 7, 10, 11, 14, 15, 18, 19]
# it works on any array
every_other_two %w{one two three four five six} # => ["three", "four"]
以下是一个适用于无限流的解决方案:
enum = Enumerator.new do |y|
(2...1/0.0).each_slice(4) do |slice|
slice[0 .. 1].each { |n| y.yield(n) }
end
end
enum.first(10) #=> [2, 3, 6, 7, 10, 11, 14, 15, 18, 19]
enum.each do |n|
puts n
end
为了好玩,使用惰性枚举需要Ruby 2.0或gem enumerable lazy:
(2..Float::INFINITY).step(4).lazy.map(&:to_i).flat_map { |x| [x, x+1] }.first(8)
#=> => [2, 3, 6, 7, 10, 11, 14, 15]
单衬里:
(0..20).to_a.reduce([0,[]]){|(count,arr),ele| arr << ele if count%4 > 1;
[count+1,arr] }.last
说明:
以0、[]为单位开始reduce外观,arr vars
如果满足条件,则将当前元素添加到数组中。块返回下一次迭代的增量和arr
不过我同意,这不是一个简单的句子,看起来有点复杂。这里是塞尔吉奥的一个更一般的回答
module Enumerable
def every_other(slice=1)
mod = slice*2
res = select.with_index { |_, i| i % mod >= slice }
block_given? ? res.map{|x| yield(x)} : res
end
end
irb> (0...20).every_other
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
irb> (0...20).every_other(2)
=> [2, 3, 6, 7, 10, 11, 14, 15, 18, 19]
irb> (0...20).every_other(3)
=> [3, 4, 5, 9, 10, 11, 15, 16, 17]
irb> (0...20).every_other(5) {|v| v*10 }
=> [50, 60, 70, 80, 90, 150, 160, 170, 180, 190]
数组停止,或者您需要一个无限可枚举项?为什么需要输入一个空ux,idx?它可以很好地使用:def every_other_two arr arr.select.with_index do | idx | idx%4>1 end-end这是一个很好的棘手解决方案+1:@K.M.RakibulIslam:对于未来,请使用以下服务。不可能在注释中发布可读代码。哦,明白了:对于第二个数组,我们需要uz:谢谢:
module Enumerable
def every_other(slice=1)
mod = slice*2
res = select.with_index { |_, i| i % mod >= slice }
block_given? ? res.map{|x| yield(x)} : res
end
end
irb> (0...20).every_other
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
irb> (0...20).every_other(2)
=> [2, 3, 6, 7, 10, 11, 14, 15, 18, 19]
irb> (0...20).every_other(3)
=> [3, 4, 5, 9, 10, 11, 15, 16, 17]
irb> (0...20).every_other(5) {|v| v*10 }
=> [50, 60, 70, 80, 90, 150, 160, 170, 180, 190]