user2270029
user2270029

Reputation: 871

Turn number into day of week - Ruby

I have this data:

data = [{"day":0,"count":1.0},{"day":1,"count":1.1666666666666667},{"day":2,"count":2.625},{"day":3,"count":2.0},{"day":4,"count":3.8},{"day":5,"count":1.2},{"day":6,"count":41.666666666666664}]

I've tried a couple different ways, but can't figure it out. Is there a way to turn the day integer into a day of the week (e.g. "Sunday" is 0), and then have them start at Monday, so the end result would be:

[{"day":"Monday","count":1.1666666666666667},{"day":"Tuesday","count":2.625},{"day":"Wednesday","count":2.0},{"day":"Thursday","count":3.8},{"day":"Friday","count":1.2},{"day":"Saturday","count":41.666666666666664}, {"day":"Sunday","count":1.0}]

Thanks for your help in advance.

Upvotes: 0

Views: 553

Answers (3)

MrPizzaFace
MrPizzaFace

Reputation: 8086

The data var that you are showing is actually JSON which means you must require 'json' so that ruby is able to parse it.

Next we require 'date' so that we can use ruby to convert your days from numbers to words.

Lastly we convert the data object back to JSON so that you can use it however it was intended.

require 'date'
require 'json'

day = Proc.new { |d| Date::DAYNAMES[d] }

data = '[ {"day":0,"count":1.0},
          {"day":1,"count":1.1666666666666667},
          {"day":2,"count":2.625},
          {"day":3,"count":2.0},
          {"day":4,"count":3.8},
          {"day":5,"count":1.2},
          {"day":6,"count":41.666666666666664} ]'

new_data = JSON.parse(data).map do |n| 
  { "day" => day.call(n["day"]), "count" => n["count"]  }.to_json
end

puts new_data

Upvotes: 1

jmromer
jmromer

Reputation: 2236

I think what you're looking for is

require 'json'
require 'date'

data = '[{"day":0,"count":1.0},{"day":1,"count":1.1666666666666667},{"day":2,"count":2.625},{"day":3,"count":2.0},{"day":4,"count":3.8},{"day":5,"count":1.2},{"day":6,"count":41.666666666666664}]'

dates = JSON.parse(data).rotate.map do |hsh| 
          week_day = Date::DAYNAMES[hsh["day"]]
          { "day" => week_day, "count" => hsh["count"]  }
        end

puts dates.to_json

#=> [{"day":"Monday","count":1.1666666666666667},{"day":"Tuesday","count":2.625},{"day":"Wednesday","count":2.0},{"day":"Thursday","count":3.8},{"day":"Friday","count":1.2},{"day":"Saturday","count":41.666666666666664},{"day":"Sunday","count":1.0}]

Upvotes: 3

rafroehlich2
rafroehlich2

Reputation: 1358

You can use the predefined DAYNAMES array in the Date module.

require 'date'
data.map! { |element| element[:day] = Date::DAYNAMES.rotate[element[:day]] }

This will convert your integer into a named day starting with Monday as zero.

Upvotes: 1

Related Questions