一种干净的写循环方式

时间:2016-08-15 02:58:08

标签: ruby-on-rails-4

在这里,我得到了工作日的有序数组。它适用于我,但看起来非常糟糕。纯垃圾)。有没有(我相信有一个)任何方法可以重构它?(看起来更干净?)

  def weekdays
    (deduct_weekdays.map{|day| day.strftime("%A")}).reverse!
  end

  private
  def deduct_weekdays
  arr = []
  @n = 0
  7.times do 
    arr << DateTime.now - @n      
    @n += 1
  end
  arr
end

2 个答案:

答案 0 :(得分:0)

这样怎么样?

require 'date'

def deduct_weekdays
  arr = []
  n = 0
  7.times do 
    arr << (Date.today - n).strftime("%A")
    n += 1
  end
  arr.reverse!
end

# returns:
["Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "Monday"]

它返回与上面相同的结果,但只返回1次。

答案 1 :(得分:0)

(6.days.ago.to_date..Date.today).collect{|d|d.strftime('%A')}