Ruby Array Operations Questions

Asked 2 years ago, Updated 2 years ago, 116 views

We have the following data that we grouped by date in Ruby.

{"[2021, 12, 28, 1]":2,
 "[2021, 12, 28, 2]":2,
 "[2021, 12, 28, 3]":2,
 "[2021, 12, 28, 4]":4,
 "[2021, 12, 28, 7]":2,
 "[2021, 12, 28, 5]":1}

I would like to convert this data as follows, but I would appreciate it if you could let me know if there are any good algorithms or techniques that can be converted smartly.

{["December 28, 2021", 1]: 2,
 ["December 28, 2021", 2]: 2,
 ["December 28, 2021", 3]: 2,
 ["December 28, 2021", 4]: 4,
 ["December 28, 2021", 7]: 2,
 ["December 28, 2021", 5]:1}

Thank you for your cooperation.

ruby array

2022-09-30 17:38

2 Answers

Second block

{["December 28, 2021", 1]: 2,
 ["December 28, 2021", 2]: 2,
 ["December 28, 2021", 3]: 2,
 ["December 28, 2021", 4]: 4,
 ["December 28, 2021", 7]: 2,
 ["December 28, 2021", 5]:1}

I don't think is strictly Ruby's correct grammar, but assume it means Hash below.

{["December 28, 2021", 1] =>2,
 ["December 28, 2021", 2] =>2,
 ["December 28, 2021", 3] =>2,
 ["December 28, 2021", 4] =>4,
 ["December 28, 2021", 7] =>2,
 ["December 28, 2021", 5] =>1}

For example, if you try to be honest about what is written in the question, it will look like this.

require 'date'

a = {"[2021, 12, 28, 1]": 2,
    "[2021, 12, 28, 2]":2,
    "[2021, 12, 28, 3]":2,
    "[2021, 12, 28, 4]":4,
    "[2021, 12, 28, 7]":2,
    "[2021, 12, 28, 5]":1}
    
a2 = a. transform_keys do | k |
  e=eval(k.to_s)
  raise"#{e}"if e.size!=4#Check just in case
  n = e.pop
  d = Date.new(*e)
  [d.strftime ("%Y year %m month %d day"), n]
end

However, I think it is a little unnatural to have the need to make a transformation like the question.Therefore, it may be better to review the direction in which this deformation does not need to be done.


2022-09-30 17:38

a={
  "[2021, 12, 28, 1]":2, "[2021, 12, 28, 2]":2, "[2021, 12, 28, 3]":2,
  "[2021, 12, 28, 4]":4, "[2021, 12, 28, 7]":2, "[2021, 12, 28, 5]":1
}

b = a.transform_keys { | k |
      *i,n=k.to_s.scan(/\d+/)
      [i.zip("date".chars).join, n.to_i]}

pb

#
{
  ["December 28, 2021", 1] =>2,
  ["December 28, 2021", 2] =>2,
  ["December 28, 2021", 3] =>2,
  ["December 28, 2021", 4] =>4,
  ["December 28, 2021", 7] =>2,
  ["December 28, 2021", 5] =>1
}


2022-09-30 17:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.