Reputation: 779
I've an YAML array:
myarray:
- PHP
- Perl
- Python
How to convert it into bash array with ruby ?
Arr[0]='PHP'
Arr[1]='Perl'
Arr[2]='Python'
Upvotes: 1
Views: 3062
Reputation: 246744
The bash mapfile
command is useful to convert lines of stdin into an array:
$ cat file.yaml
myarray:
- PHP
- Perl
- Python
- element with spaces
$ mapfile -t array < <(ruby -ryaml -e 'yaml = YAML.load(File.read(ARGV.shift)); puts yaml["myarray"].join("\n")' file.yaml)
$ for i in "${!array[@]}"; do echo "$i ${array[i]}"; done
0 PHP
1 Perl
2 Python
3 element with spaces
This avoids having to use eval
in the shell
Upvotes: 2
Reputation: 1567
I'm not sure if this is what you want.
In ruby, parse the yaml array and write an output for Bash to read as an array:
require 'yaml'
yaml_array = <<-eos
myarray:
- PHP
- Perl
- Python
eos
yaml = YAML.load(yaml_array)
print "(#{yaml["myarray"].join(' ')})"
This ruby script will print (PHP Perl Python)
to stdout.
You can then use it in Bash:
$ eval array=$(ruby ruby_script.rb)
$ echo ${array[0]}
PHP
$ echo ${array[1]}
Perl
Upvotes: 3
Reputation: 1288
require 'yaml'
yaml_text = "myarray:
- PHP
- Perl
- Python"
yaml = YAML.load(yaml_text)
array = yaml["myarray"]
puts array.class #=> Array
puts array #=> PHP
#=> Perl
#=> Python
Upvotes: 2