tonio94
tonio94

Reputation: 510

Ruby - store in array and return all values

So I have a shell command with this kind of output :

sqoop-client - 2.6.4.0-91
sqoop-server - 2.6.4.0-91
storm-slider-client - 2.6.4.0-91
tez-client - 2.6.4.0-91
zookeeper-client - 2.6.4.0-91
zookeeper-server - 2.6.4.0-91

I want to store this output (service name & service version) in an array then return all the objects.

At this moment in my code I already return some fixed values like that :

#code :

 return {
   hdp_version: Facter::Core::Execution.execute('/usr/bin/hdp-select versions | tail -1'),
   sqoop: File.exist?('/etc/sqoop'),
 }

#output :
{
  hdp_version => "2.6.4.0-91",
  sqoop => false
}

How can I store the output from the shell command in a 2D array and parse all the values to return them like the example above?

Like this (but in a loop):

obj[0][0] : obj[0][1], 
obj[1][0] : obj[1][1],
[...]

Thanks

Upvotes: 0

Views: 186

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

Considering you have such an output, you just need to iterate every line in the output, split the line by " - " and store it in the result hash:

libs = "sqoop-client - 2.6.4.0-91\n" \
"sqoop-server - 2.6.4.0-91\n" \
"storm-slider-client - 2.6.4.0-91\n" \
"tez-client - 2.6.4.0-91\n" \
"zookeeper-client - 2.6.4.0-91\n" \
"zookeeper-server - 2.6.4.0-91\n"

libs_with_versions = libs.each_line.with_object({}) do |line, result|
  lib, version = line.strip.split(" - ")
  result[lib] = version
end

puts libs_with_versions

returns:

{
   "sqoop-client" => "2.6.4.0-91",
   "sqoop-server" => "2.6.4.0-91",
   "storm-slider-client" => "2.6.4.0-91",
   "tez-client" => "2.6.4.0-91",
   "zookeeper-client" => "2.6.4.0-91",
   "zookeeper-server"=>"2.6.4.0-91"
}

Upvotes: 2

Related Questions