2013-10-11 120 views
0

我正在創建一個12個月的線圖,其中包含前12個月的數據。當前月份或第12個訂單項應顯示爲OCT 13。第一行應該說OCT 12Ruby中的當前月/年和上個月/年的下拉

我該如何寫一些東西來動態拉動當前月份以及之前的11個月,一直回到去年的當前月份。我遇到的問題是確保去年十月在2012年被標記爲一個月,但在3個月內,我需要將1月標記爲2013,而不用更改代碼。

+1

如果你有從2012年10月到2013年10月的每個月的列表,那麼你將有一個13個元素的列表,而不是12個。當前月份不會是第12個項目(索引11),但將是13日(索引12)。 – sawa

回答

1

使用<<操作了一個月

require "date" 

12.downto(0).map{ |d| (Date.today << d).strftime("%^b %y") } 
#=> ["OCT 12", "NOV 12", "DEC 12", "JAN 13", "FEB 13", "MAR 13", "APR 13", 
#  "MAY 13", "JUN 13", "JUL 13", "AUG 13", "SEP 13", "OCT 13"] 

使用@ Stefan的輸入順序更改爲轉移的日期。

+0

或簡單地'(Date.today << d).strftime(「%b%Y」)'也許'12.downto(0)' – Stefan

+0

@Stefan好建議......我保持秩序,因爲它取決於OP想要什麼命令。 – tihom

+0

*「第一行應該說OCT 12」* – Stefan

2
a = [Date.today.prev_year] 
12.times{a.push(a.last.next_month)} 
a.map{|d| d.strftime("%^b %y")} 

# => [ 
    "OCT 12", 
    "NOV 12", 
    "DEC 12", 
    "JAN 13", 
    "FEB 13", 
    "MAR 13", 
    "APR 13", 
    "MAY 13", 
    "JUN 13", 
    "JUL 13", 
    "AUG 13", 
    "SEP 13", 
    "OCT 13" 
] 
0
require 'date' 

def last_n_months(n, format='%^b %Y') 
    (n+1).times.map { |i| (Date.today << i).strftime(format) } 
end 

last_n_months(12) 
# => ["OCT 2013", "SEP 2013", "AUG 2013", "JUL 2013", "JUN 2013", "MAY 2013", "APR 2013", "MAR 2013", "FEB 2013", "JAN 2013", "DEC 2012", "NOV 2012", "OCT 2012"] 
0

是,使用Date#methods的是去這裏的路,是的,他們都需要得到今天的日期,但不會是更令人滿意滾你自己?這裏有一種方法:

# Assume start_year falls in current millenium. 1 <= start_month <= 12 

MONTHS = %q[JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC].split 

def doit(start_year, start_month) 
    pairs = (((start_month-1)..11).to_a.product [start_year-1]) + 
    ((0..(start_month-1)).to_a.product [start_year]) 
    pairs.map! {|p| MONTHS[p.first] + " #{p.last.to_s}"}.reverse 
end 

p doit(13, 10) 

首先創建pairs =>

[[9, 12], [10, 12], [11, 12]] + 
[[0, 13], [1, 13], [2, 13], [3, 13], [4, 13], [5, 13], [6, 13], [7, 13], [8, 13], [9, 13]] 

這是

[[9, 12], [10, 12], [11, 12], [0, 13], [1, 13], [2, 13], [3, 13], 
[4, 13], [5, 13], [6, 13], [7, 13], [8, 13], [9, 13]] 

然後用含有月份縮寫,一年字符串替換對元素。

["OCT 13", "SEP 13", "AUG 13", "JUL 13", "JUN 13", "MAY 13", "APR 13", 
"MAR 13", "FEB 13", "JAN 13", "DEC 12", "NOV 12", "OCT 12"]      

我明顯需要所有括號來計算pairs。任何人都可以解釋爲什麼我需要在第二行的外部?