1

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
3
  • What's hostnames? Can you add what that variable holds? Commented Aug 28, 2022 at 13:47
  • hostnames is a database query. It has IP, name, id etc. I want to pick only IP and create a comma separated list. It prints IP correctly for each host but I just need to create a list Commented Aug 28, 2022 at 13:52
  • There is no comma separated list in Ruby :) What do you mean? What's your input? What's expected output? Please edit your question Commented Aug 28, 2022 at 13:55

3 Answers 3

3

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 host.name.match(/some_regex/)
  host.ip
}.compact # b/c otherwise you'll end up with some nil entries
Sign up to request clarification or add additional context in comments.

5 Comments

This. Internalising the functional programming concepts map/filter/reduce will get you very far. Less mutable state and fewer if/else constructs, too.
Need to use each loop because I have conditions in the loop.
What do those conditions look like?
@Robert you can include conditions in the collect iterator. I used a shorthand syntax, but I edited my answer to show the longer syntax, with conditions
You could use each_with_object to avoid compact.
0

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

Comments

0

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(", ")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.