0

I am looking to extract keys and values from a hash. I manage to retrieve the data but in the wrong format. I am doing the following:

@message_count_series = @messages.collect { |p| "[#{p["created_at"]}, #{p["total_cnt"]}]" }
 => ["[2021-12-02 13:21:19.837233, 3]", "[2021-11-20 13:54:54.846048, 3]"] 

What I would like to obtain is:

 => [[2021-12-02 13:21:19.837233, 3], [2021-11-20 13:54:54.846048, 3]] 

Just without the quote (not a string).

I tried the following :

@message_opened_series = @messages.collect { |p| ["#{p["created_at"]}, #{p["opened_cnt"]}"] }
 => [["2021-12-02 13:21:19.837233, 1"], ["2021-11-20 13:54:54.846048, 0"]] 

Which takes me closer, but now my data are considered a string inside the array.

The following appear to work, but might not be very robust

@message_opened_series = @messages.collect { |p| [DateTime.parse("#{p["created_at"]}"), ("#{p["opened_cnt"]}").to_i] }
 => [[Thu, 02 Dec 2021 13:21:19 +0000, 1], [Sat, 20 Nov 2021 13:54:54 +0000, 0]] 

Is there a better way to do this please ?

2
  • 2
    How does your original hash look like? What is the data type of the values in the original hash? Why do you think that your last version, that works, might not be robust? Is it possible that the hash contains invalid data? Commented Dec 4, 2021 at 7:05
  • 2
    Your desired result is not a legal Ruby object, therefore, you cannot possibly get this result. Commented Dec 4, 2021 at 10:20

1 Answer 1

1
@message_opened_series =
  @messages.collect { |p| [p["created_at"].to_s, p["opened_cnt"]] }
 => [["2021-12-02 13:21:19.837233", 3], ["2021-11-20 13:54:54.846048", 3]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.