Ruby:将日期作为小数转换为日期作为名称

前端之家收集整理的这篇文章主要介绍了Ruby:将日期作为小数转换为日期作为名称前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以快速将strftime(“%u”)值转换为strftime(“%A”),或者我是否需要构建等价散列,如{“Monday”=> 1,………“星期日”=> 6}

我有一个数组,有一天作为十进制值

  1. class_index=[2,6,7]

我想循环遍历这个数组来构建和数组这样的天名

  1. [nil,"Tuesday",nil,"Saturday","Sunday"]

所以我能做到

  1. class_list=[]
  2. class_index.each do |x|
  3. class_list[x-1] = convert x value to day name
  4. end

这甚至可能吗?

解决方法

怎么样:
  1. require "date"
  2. DateTime.parse("Wednesday").wday # => 3

哦,我现在看到你扩大了你的问题.怎么样:

  1. [2,7].inject(Array.new(7)) { |memo,obj| memo[obj-1] = Date::DAYNAMES[obj%7]; memo }

让我解释一下:

  1. input = [2,7]
  2. empty_array = Array.new(7) # => [nil,nil]
  3. input.inject(empty_array) do |memo,obj| # loop through the input,and
  4. # use the empty array as a 'memo'
  5. day_name = Date::DAYNAMES[obj%7] # get the day's name,modulo 7 (Sunday = 0)
  6. memo[obj-1] = day_name # save the day name in the empty array
  7. memo # return the memo for the next iteration
  8. end

Ruby的美丽.

猜你在找的Ruby相关文章