Rails 本地化月份和日期数组中出现 nil 条目的原因是什么?
What is the reason for the nil entry in Rails localisation month and day arrays?
我正在使用 Rails i18n,我注意到几个月来必须输入 nil(如此处文档中所述:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15_),如下所示:
month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December]
因为没有第 0 个月这样的东西。
为什么这很重要,为什么不返回第一个元素的 January?这是如何工作的?
他们可能只是想让数组索引与正确的月份相对应,所以他们在前面贴了一个存根。
例如
months[12] = December
这是因为自然月数是基于 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
我正在使用 Rails i18n,我注意到几个月来必须输入 nil(如此处文档中所述:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15_),如下所示:
month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December]
因为没有第 0 个月这样的东西。
为什么这很重要,为什么不返回第一个元素的 January?这是如何工作的?
他们可能只是想让数组索引与正确的月份相对应,所以他们在前面贴了一个存根。
例如
months[12] = December
这是因为自然月数是基于 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