Home > OS >  Ruby - Create key value pairs from variable
Ruby - Create key value pairs from variable

Time:03-10

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"}

CodePudding user response:

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"}

CodePudding user response:

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
  •  Tags:  
  • ruby
  • Related