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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With