1, ......... \"Sunday\" => 6}" />
开发者

Ruby: convert day as decimal to day as name

Is it possible to convert quickly a strftime("%u") value to a strftime("%A") or do i need to build an equivalence hash like {"Monday" => 1, ......... "Sunday" => 6}

I have an Array with some day as decimal values

class_index=[2,6,7]

and I would like to loop through this array to build and array of days name like this

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

so I could do

class_list=[]
class_index.each do |x|
  class_list[x-1] = convert x value to da开发者_JAVA百科y name
end

Is that even possible?


How about:

require "date"
DateTime.parse("Wednesday").wday # => 3

Oh, I now see you've expanded your question. How about:

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

Let me explain that one:

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

The beauty of Ruby.


To go from decimal to weekday:

require 'date'
Date::DAYNAMES[1]
# => "Monday"

So, in your example, you could simply do:

class_list=[]
class_index.each do |x|
  class_list[x-1] = Date::DAYNAMES[x-1]
end


Here’s one way that comes to mind:

require "date"

def weekday_index_to_name(index)
  date = Date.parse("2011-09-26") # Canonical Monday.
  (index - 1).times { date = date.succ }
  date.strftime("%A")
end


class_index=[2,6,7]

class_index.map{|day_num| Date::DAYNAMES[day_num%7]}

#=> ["Tuesday", "Saturday", "Sunday"]

note that day names are from 0 to 6, so you can either work from 0 to 6 or have it modulo 7

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜