Ruby: convert day as decimal to day as name

Is it possible to quickly convert the value of strftime ("% u") to strftime ("% A") or do I need to build an equivalence hash, for example {"Monday" => 1, ......... "Sunday" => 6}

I have an Array with some day as decimal values

class_index=[2,6,7] 

and I would like to skip this array to build and the array of days, like this

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

so i can do

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

Is it possible?

+6
source share
4 answers

What about:

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

Oh, now I see that you have expanded your question. What 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 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.

+6
source

Transition from decimal to weekday:

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

So in your example you can just do:

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

Here is 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 
+1
source
 class_index=[2,6,7] class_index.map{|day_num| Date::DAYNAMES[day_num%7]} #=> ["Tuesday", "Saturday", "Sunday"] 

Please note that the names of the days are from 0 to 6, so you can work from 0 to 6 or have modulo 7

0
source

Source: https://habr.com/ru/post/898087/


All Articles