Vlad Cenan Vlad Cenan - 2 years ago 74
Ruby Question

How can I map each value found into a diffrent variable

I want to create a chef recipe and I'm stuck at this step:

members = search("node", "recipe:redis AND chef_environment:#{node.chef_environment}") || []
members.each do |node|
puts "#{node["ipaddress"]}"

This is working and returning me the IP addresses for those three servers found.
But I want to assign/give each VALUE found (ip address) to a variable because I will run a command like the following:

execute 'command' do
command "redis-trib.rb create --replicas 1 #{node1}:6379 #{node2}:6379 #{node3}:6379 #{node1}:6380 #{node2}:6380 #{node3}:6380"

Answer Source

You can do something like this:

nodes = members.map do |node|

And then use it like this:

execute 'command' do
  command "redis-trib.rb create --replicas 1 #{nodes[0]}:6379 #{nodes[1]}:6379 #{nodes[2]}:6379 #{nodes[0]}:6380 #{nodes[1]}:6380 #{nodes[2]}:6380"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download