简体   繁体   中英

Ruby gsub array elements to reformat

Wanted to see if I could get some help with reformatting some elements in an array so they are output a certain way. Here's what I have so far:

node = gets.chomp
nodelist = `knife node list`

if nodelist.include?(node)
  cookbook_versions = `knife solve -n #{node}`.split(/\n/).drop(1)
  cookbook_versions.collect!{|element| element.gsub!(#regexhere)}
  puts cookbook_versions
else
  puts "not found"
end

Currently outputs:

7-zip 1.0.2
apache2 2.0.0
apt 2.6.0
ark 0.9.0

I want it to look like this:

"7-zip": "1.0.2",
"apache2": "2.0.0",
"apt": "2.6.0",
"ark": "0.9.0"

Anyone know some regex that could help me do that? or any other way? I put #regexhere in the code above because my attempts so far today haven't even come close.

You have an array of lines like

["7-zip 1.0.2", "apache2 2.0.0"]

and want to transform them into a key-value list (though I suspect you actually want json).

node = gets.chomp
nodelist = `knife node list`

if nodelist.include?(node)
  cookbook_versions = `knife solve -n #{node}`.split(/\n/).drop(1).map {|line| line.split(" ", 2) }
  puts JSON.pretty_generate Hash[*cookbook_versions.flatten]
else
  puts "not found"
end

By means of demonstration:

# Given:
x = ["apache2 1.9.6", "iptables 0.12.0", "logrotate 1.5.0", "pacman 1.1.1"]

> puts JSON.pretty_generate Hash[*x.flat_map {|line| line.split(" ", 2) }]
{
  "apache2": "1.9.6",
  "iptables": "0.12.0",
  "logrotate": "1.5.0",
  "pacman": "1.1.1"
}

If you want it without the enclosing braces, you may just want to iterate and display the list manually:

if nodelist.include?(node)
  cookbook_versions = `knife solve -n #{node}`.split(/\n/).drop(1).map {|line| line.split(" ", 2) 
  puts cookbook_versions.map {|line| format('"%s": "%s"', *line) }.join(",\n")
else
  puts "not found"
end

With output:

"apache2": "1.9.6",
"iptables": "0.12.0",
"logrotate": "1.5.0",
"pacman": "1.1.1"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM