Search code examples
ruby-on-railsrubyruby-on-rails-4

Create comma separated array using each loop


How can I create list of IP address with comma separated when using each loop?

ip_list = [];
hostnames.each do |host|
  puts host.ip  
end

I tried ip_list.join but that isn't working at all. I want all the host IP in a variable with comma seperated.

I want the output to be comma separated string.

Example:

puts ip_list
10.10.10.10, 10.10.10.11

Solution

  • How about this? You can use Array#push.

    ip_list = [];
    hostnames.each do |host|
      ip_list.push host.ip  
    end
    p ip_list
    

    Or, Array#map would be more useful.

    ip_list = hostnames.map { |host| host.ip }
    p ip_list