2016-07-14 17 views
0

我使用Rails的國際化,我注意到,對於個月零必須輸入(如文檔在這裏提到:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15_)是這樣的:在Rails本地化月份和日期數組中輸入nil的原因是什麼?

month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December] 

,因爲沒有這樣的事,作爲一個零一個月。

爲什麼這很重要,爲什麼不是1月份剛回來的第一個元素?這個怎麼用?

回答

1

這是因爲自然月數是1爲基礎的,而不是被0爲基礎的像一個典型的陣列。爲了提供這一點,並避免必須記住在需要時執行索引計算,月份名稱數組剛好在zero位置處使用額外元素定義。

看看date_helper code對於如何使用它的例子:

# Looks up month names by number (1-based): 
    # 
    # month_name(1) # => "January" 
    # 
    # If the <tt>:use_month_numbers</tt> option is passed: 
    # 
    # month_name(1) # => 1 
    # 
    # If the <tt>:use_two_month_numbers</tt> option is passed: 
    # 
    # month_name(1) # => '01' 
    # 
    # If the <tt>:add_month_numbers</tt> option is passed: 
    # 
    # month_name(1) # => "1 - January" 
    # 
    # If the <tt>:month_format_string</tt> option is passed: 
    # 
    # month_name(1) # => "January (01)" 
    # 
    # depending on the format string. 
    def month_name(number) 
     if @options[:use_month_numbers] 
     number 
     elsif @options[:use_two_digit_numbers] 
     '%02d' % number 
     elsif @options[:add_month_numbers] 
     "#{number} - #{month_names[number]}" 
     elsif format_string = @options[:month_format_string] 
     format_string % {number: number, name: month_names[number]} 
     else 
     month_names[number] 
     end 
    end 
1

他們可能只是想要數組索引對應正確的月份,所以他們堅持前面的存根。

例如

months[12] = December 
相關問題