fajarhide
fajarhide

Reputation: 35

avoid to print response '200' the if conditions in ruby

I'm still learning ruby, and there seems to be a problem with my code that i can't figure out

require 'net/http'

File.open("html.txt", "r") do |file_handle|
  file_handle.each_line do |server|
    uri = URI( server )
    res = Net::HTTP.get_response(uri) 
    if res.code != 200
        puts " #{uri} => #{res.code}"
    end
  end
end

html.txt

http://stackoverflow.com
http://google.com
http://facebook.com
http://serverfault.com
http://twitter.com

I don't want to print out the URI's which has a response '200'

But right now this is what gets printed:

 http://stackoverflow.com => 200
 http://google.com => 302
 http://facebook.com => 302
 http://serverfault.com => 200
 http://twitter.com => 301

This is my expected output:

 http://google.com => 302
 http://facebook.com => 302
 http://twitter.com => 301

Can anyone help me with this..? thanks in advance.

Upvotes: 0

Views: 276

Answers (1)

Alfie
Alfie

Reputation: 2784

The response code is a string.

You should be using the condition res.code != '200', note the quotes.

Your code should look like this:

require 'net/http'

File.open("html.txt", "r") do |file_handle|
  file_handle.each_line do |server|
    uri = URI( server )
    res = Net::HTTP.get_response(uri)
    if res.code != '200'
        puts " #{uri} => #{res.code}"
    end
  end
end

Upvotes: 3

Related Questions