Ruby create Hash from existing Array

Hello,
I have an array(as a string) as below.

["Flask running\nFlask_Medium running\ngrafana shutoff\nPrometheus shutoff\nredismaster shutoff\nredisslave shutoff\nredisslave2 shutoff\n"]

I need to convert above as a Hash as below.

Flask==>running
Flask_Medium==>running
grafana==>shutoff
.
.
.

Can anyone please suggest how to do this?

Hello Chandan,

You can achieve this with the following:

str = "Flask running\nFlask_Medium running\ngrafana shutoff\nPrometheus shutoff\nredismaster shutoff\nredisslave shutoff\nredisslave2 shutoff\n"
array = str.split("\n")
hash = {}
array.each do |item|
  k, v = item.split(' ')
  hash[k] = v
end

Now hash will hold the required key-value pairs.

Hi @robert-b ,

It works very well ! Thank you .

Just a slight modification I had to make as it is an array actually.

@array = str.split("\\n")

Hi @robert-b

More often, I see that when passing variables from Ruby to Javascript, there are these characters like double quotes(") and the character “[” & “]” which appears in the webpage. How do we remove such characters? Below is the hash data stored in hash variable.

{"[\"Flask"=>"running", "Flask_Medium"=>"running", "grafana"=>"shutoff", "Prometheus"=>"shutoff", "redismaster"=>"shutoff", "redisslave"=>"shutoff", "redisslave2"=>"shutoff", "\"]"=>nil}

So we can use hash.keys and hash.values to get the keys and values.

Ruby Code

hashkeys = hash.keys
hashvalues = hash.values

I need to populate the above key,values in a HTML table and hence in my index.html.erb file I use below to extract the above key and values.

Javascript code:

var myvar = '<%=j hashkeys %>'; 
var myvar1 = '<%=j hashvalues %>';
let my = myvar.split(',');
let my1 = myvar1.split(',');

However on the webpage, I still see the double quotes and “[” & “]” characters displayed.

So, I tried upon it and applied the Javascript replace method on the key and values to remove the unwanted double quotes and “[” and “]” characters and finally my HTML table looks clean now.