是否可以快速将strftime(“%u”)值转换为strftime(“%A”),或者我是否需要构建等价散列,如{“Monday”=> 1,………“星期日”=> 6}
我有一个数组,有一天作为十进制值
- class_index=[2,6,7]
我想循环遍历这个数组来构建和数组这样的天名
- [nil,"Tuesday",nil,"Saturday","Sunday"]
所以我能做到
- class_list=[]
- class_index.each do |x|
- class_list[x-1] = convert x value to day name
- end
这甚至可能吗?
解决方法
怎么样:
- require "date"
- DateTime.parse("Wednesday").wday # => 3
哦,我现在看到你扩大了你的问题.怎么样:
- [2,7].inject(Array.new(7)) { |memo,obj| memo[obj-1] = Date::DAYNAMES[obj%7]; memo }
让我解释一下:
- input = [2,7]
- empty_array = Array.new(7) # => [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
Ruby的美丽.