Good morning,
I'm starting on Ruby, wanted to create a small tool that fetches my public IP and sends it over by email. I'm stumbling on a basic problem with a string comparison and an if/else block that won't process.
Code is quite simple (see below). The problem comes at the string comparison at line 21. What I'd want is that whenever the IP address changed from what was recorded in a file, the new IP overwrites the one in the file, and other actions (not in the current code) will ensue.
It looks like that sometimes the comparison is not executed, thus the statements following the if do not execute.
I'd like to understand why is that. Line 21 has been changed at times for if (!oldIP == ip) to if (oldIP != ip), same result. I also suspect the return value to be ignored (dead code path ?) sometimes.
Here's the code
#!/usr/bin/env ruby
require "net/http"
puts "\e[H\e[2J"
def FetchIPAddress()
oldIP = ""
if File::exists?('/tmp/wanipaddress.txt')
iFile = File.open('/tmp/wanipaddress.txt')
oldIP = iFile.read()
iFile.close()
end
oFile = File.open('/tmp/wanipaddress.txt', "w+")
ip = Net::HTTP.get(URI("https://api.ipify.org"))
puts "old = " + oldIP
puts "new = " + ip
if (!oldIP == ip)
puts "changed"
oFile.puts ip
oFile.close()
else
ip = "unchanged"
puts "unchanged"
end
return ip
end
Really, I do see some erratic behaviour here; I suspect it's just me being a newbie with Ruby.
if (oldIP != ip)does not correct the problem? Note you open the file for writing, but only write to it when theifclause istrue. If theifclause isfalsethe (then empty) file will be closed by Ruby when you return from the method. That is wrong but also will cause confusion when running your code. One moment your current IP is saved to file, the next it is no longer there! Try this (after removingofile = ...):if (oldIP != ip); puts "changed"; File.write('/tmp/wanipaddress.txt', ip); else....oFile.puts ipadds a newline to the ip before writing it to file. For example, "154.5.147.124\n". When that is read it obviously will not match the current ip, which doesn't end with a newline. Note too that, by convention, "snake-case" is used when naming methods (and variables). Among other things, what means they begin with a lower-case letter.FetchIPAddress, though it works, is a constant because it begins with a capital letter. The snake-case equivalent isfetch_ip_addressorfetch_IP_address.