按键整数重新排序整数数组
  我有多达7个整数代表每周的每一天0 ... 6 (太阳 - 星期六) 
  current day = 3 (星期三)。 
  我如何重新排列整数数组,以便最接近星期三( 3 )的数字排在第一位。 
例如:
Current Day = 3
Days (input) = [0, 1, 2, 3, 4, 5, 6]
Correct Output = [3, 4, 5, 6, 0, 1, 2]
  但数组可能不包含所有日期(例如current day可能会丢失): 
Current Day = 3
Days (input) = [0, 2, 4, 6]
Correct Output = [4, 6, 0, 2]
  基本上重新排序数组,以便current day (或前一个整数) 
  目前的尝试:我研究过使用a.rotate,但如果current day不在阵列中,我不确定如何处理。 
  我也尝试使用min_by但它不循环整数 
@days.min_by { |x| (x.to_f - Time.now.wday).abs } 
如果你正在寻找当天之后的日子:
my_array.sort_by{|x| (x-current_day)%7}
  如果您只想查找第一个数字,只需使用min_by而不是sort_by 
并与您的意见:
irb(main):059:0* my_array = [0, 1, 2, 3, 4, 5, 6]
=> [0, 1, 2, 3, 4, 5, 6]
irb(main):060:0> current_day = 3
=> 3
irb(main):061:0> my_array.sort_by{|x| (x-current_day)%7}
=> [3, 4, 5, 6, 0, 1, 2]
irb(main):062:0> my_array = [0, 2, 4, 6]
=> [0, 2, 4, 6]
irb(main):063:0> my_array.sort_by{|x| (x-current_day)%7}
=> [4, 6, 0, 2]
所有你需要做的就是找到输入当前日期之前的整数索引,如果它本身不包含在数组中。 这里:
def mrotate(days, c_day)
  index = days.index(c_day)
  index = days.index(days.find { |d| d > c_day}) if !index
  days.rotate index || 0
end
mrotate([0, 1, 2, 3, 4, 5, 6], 3)
#=> [3, 4, 5, 6, 0, 1, 2]
mrotate([0, 2, 4, 6], 3)
#=> [4, 6, 0, 2]
您可以搜索>= 3的第一个索引,并将数组拆分为两部分: 
x = [0, 1, 2, 3, 4, 5, 6]
y = [0, 2, 4, 6]
pos = x.index{|s| s >= 3}
# => 3
x[pos..-1] + x[0..pos-1]
# [3, 4, 5, 6, 0, 1, 2]
pos = y.index{|s| s >= 3}
# => 2
y[pos..-1] + y[0..pos-1]
# => [4, 6, 0, 2]
                        链接地址: http://www.djcxy.com/p/25693.html
                        
                        
                    