Home > other >  Create comma separated array using each loop
Create comma separated array using each loop

Time:08-29

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

CodePudding user response:

I know you asked to use each but why not use collect? This gives you an array:

hostnames.collect(&:ip)

If you want a comma-separated list do:

hostnames.collect(&:ip).join(',')

If you need conditions in the iterator, you can use the longer block syntax:

hostnames.collect { |host|
  next unless hostname.match(/some_regex/)
  host.ip
}.compact # b/c otherwise you'll end up with some nil entries

CodePudding user response:

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

CodePudding user response:

If you want to get new array based on the existing one and filter by condition at the same time, you can use filter_map (was introduced in Ruby 2.7)

If you wan to get string from array just use join

hostnames.filter_map { |hostname| hostname.ip if some.condition }.join(", ")
  • Related