vendredi 3 décembre 2021

How to convert two strings into an array of two in Ruby

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 ?

Aucun commentaire:

Enregistrer un commentaire