0

I am trying to only have one of the if conditions to print.

subnet = ['10.14.1.32/27', '10.17.8.2/29']
system = gets.chomp
subnet.each do |cidr|
  address_space = NetAddr::CIDR.create(cidr)
  if address_space.contains? system
    puts "found"
  else
    puts "not found"
  end
end

the output I get for something like 10.17.8.3 would be

not found
found

How would I only get one response? I tried using breaks but that doesn't work. Thanks All!

2
  • Your code outputs one OR the other for each element of subnet. Not sure what you expect Commented Apr 19, 2016 at 19:58
  • BTW, in order to help your readers understand your intent, collections should have plural names, so 'subnet' should be 'subnets'. Commented Apr 20, 2016 at 14:55

2 Answers 2

5

The trick is to use the Enumerable#find method:

subnet = ['10.14.1.32/27', '10.17.8.2/29'].collect do |cidr|
  NetAddr::CIDR.create(cidr)
end

system = gets.chomp

found = subnet.find do |cidr|
  cidr.contains?(system)
end

if (found)
  puts "found"
else
  puts "not found"
end

That will return either the CIDR object that matched or nil if nothing did.

Sign up to request clarification or add additional context in comments.

Comments

0

subnet is an array and your code using each loop. So if subnet is more than 1 elements it will return subnet.count result. I do not know what exactly did you want. But if you want to break of loop in this case, you can using return

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.