Multilines string to hash

Hi all,

I have two lines of this type as output of a cli command:

Source | Status | Enable | IP address | Subnet mask

Static | Disabled | true | 2.2.2.2 | 255.255.0.0

I would like create a hash :

{“Source”=>“Static”, “Status”=>“Disabled”, “Enable”=>“true”, "IP
address "=>“2.2.2.2”, “Subnet mask”=>“255.255.0.0” }

Thank you

Protagora Protagora wrote in post #1171010:

Hi all,

I have two lines of this type as output of a cli command:

Source | Status | Enable | IP address | Subnet mask

Static | Disabled | true | 2.2.2.2 | 255.255.0.0

I would like create a hash :

{“Source”=>“Static”, “Status”=>“Disabled”, “Enable”=>“true”, "IP
address "=>“2.2.2.2”, “Subnet mask”=>“255.255.0.0” }

Thank you

use scan, and zip, flatten and Hash[]:
txt.scan(/[\w\d.]/)
[1,2,3].zip([‘a’,‘b’,‘c’]) >> [1,a],[2,b]…
[[1,2],[2,3],[4,5]].flatten >> [1,2,1,3,4,5]
Hash[1,2,3,4] >> {1=>2, 3=>4}

and see https://www.ruby-forum.com/topic/6873006
:slight_smile:

Protagora Protagora wrote in post #1171010:

I have two lines of this type as output of a cli command:

Let me guess: this is some relational database’s CLI. I’d export as CSV
and then use Ruby’s CSV to load the file contents and convert them to
the Hash.

Cheers

robert

There is no database. This cli command displays results in that format
and I would like to have hash structure to run tests.

Bye

Protagora

Protagora Protagora wrote in post #1171010:

l1=stdin.gets.scan(/[\w\d.]+/)
stdin.gets
l2=stdin.gets.scan(/[\w\d.]+/)

res=Hash[*(l1.zip(l2).to_a.flatten)]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs