'Ruby - Create key value pairs from variable
How to create a key value pair from the following data using ruby?
result="-e hostname=webserver001 -e username=root -e password=testing123"
I want to parse it and produce and produce the following output:
{"hostname"=>"webserver001", "username"=>"root", "password"=>"testing123"}
Solution 1:[1]
result = "-e hostname=webserver001 -e username=root -e password=testing123"
Code
p result.scan(/\w+=\w+/)
.map { _1.split("=") }
.to_h
Or
p Hash[result.scan(/\w+=\w+/)
.map { _1.split("=") }]
Output
{"hostname"=>"webserver001", "username"=>"root", "password"=>"testing123"}
Solution 2:[2]
You can try something like :
result = " -e hostname=webserver001 -e username=root -e password=testing123"
hash = Hash.new
res = result.split(' -e ')
res.each { |x|
if x.split('=').length() > 1
part = x.split('=')
hash[part[0]] = part[1]
end
}
puts hash
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
