是否可以快速将strftime("%u")值转换为strftime("%A")或者我是否需要构建等价散列,如{"Monday"=> 1,........ ."星期日"=> 6}
我有一个数组,有一天作为十进制值
class_index=[2,6,7]
Run Code Online (Sandbox Code Playgroud)
我想循环遍历这个数组来构建和数组这样的天名
[nil, "Tuesday", nil, nil, nil, "Saturday", "Sunday"]
Run Code Online (Sandbox Code Playgroud)
所以我能做到
class_list=[]
class_index.each do |x|
class_list[x-1] = convert x value to day name
end
Run Code Online (Sandbox Code Playgroud)
这甚至可能吗?
怎么样:
require "date"
DateTime.parse("Wednesday").wday # => 3
Run Code Online (Sandbox Code Playgroud)
哦,我现在看到你扩大了你的问题.怎么样:
[2,6,7].inject(Array.new(7)) { |memo,obj| memo[obj-1] = Date::DAYNAMES[obj%7]; memo }
Run Code Online (Sandbox Code Playgroud)
让我解释一下:
input = [2,6,7]
empty_array = Array.new(7) # => [nil, nil, nil, nil, nil, nil, nil]
input.inject(empty_array) do |memo, obj| # loop through the input, and
# use the empty array as a 'memo'
day_name = Date::DAYNAMES[obj%7] # get the day's name, modulo 7 (Sunday = 0)
memo[obj-1] = day_name # save the day name in the empty array
memo # return the memo for the next iteration
end
Run Code Online (Sandbox Code Playgroud)
Ruby的美丽.
从小数到工作日:
require 'date'
Date::DAYNAMES[1]
# => "Monday"
Run Code Online (Sandbox Code Playgroud)
所以,在你的例子中,你可以简单地做:
class_list=[]
class_index.each do |x|
class_list[x-1] = Date::DAYNAMES[x-1]
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2510 次 |
| 最近记录: |