Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: convert day as decimal to day as name

Tags:

date

ruby

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 day name
end

Is that even possible?

like image 213
Yannick Schall Avatar asked Sep 26 '11 16:09

Yannick Schall


2 Answers

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.

like image 195
rdvdijk Avatar answered Sep 29 '22 11:09

rdvdijk


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
like image 32
BaronVonBraun Avatar answered Sep 29 '22 10:09

BaronVonBraun