将数字转换为星期几 - Ruby

时间:2014-01-18 02:09:57

标签: ruby

我有这些数据:

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}]

我尝试了几种不同的方式,但无法弄明白。有没有办法将日整数转换为星期几(例如“星期日”为0),然后让它们从星期一开始,所以最终结果将是:

[{"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}]

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

我认为您正在寻找的是

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}]

答案 1 :(得分:1)

您可以在Date模块中使用预定义的DAYNAMES数组。

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

这会将您的整数转换为以星期一开始为零的命名日期。

答案 2 :(得分:1)

您展示的data var实际上是JSON,这意味着您必须require 'json'以便ruby能够解析它。

接下来我们require 'date',以便我们可以使用ruby将您的日期从数字转换为单词。

最后,我们将data对象转换回JSON,以便您可以按预期使用它。

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