Can you tell me why this code gives an error?
I am not understanding this line: File.new("#{line}", "w")
system "ipconfig /all > info.txt"
info_text = File.open("info.txt")
info_text.each { |line|
if line =~ /Physical Address/
line.slice! " Physical Address. . . . . . . . . : "
File.new("#{line}", "w")
end
}
Thanks -Mike W
The code is designed to run on Microsoft Windows. The script won’t do anything useful on other OSes. In particular, it tries to create one empty file for every Network Adapter on your system, using the MAC address.
It’s very likely that
linecontains a character that Windows doesn’t allow in a filename. (Windows is more restrictive than Linux or Mac OS X.) What’s the error you’re getting?Also, try printing the
linevariable immediately before callingFile.newto see what it contains.You probably need to sanitize
lineby removing invalid characters. See this answer for what isn’t allowed. The easy way would be to use a simple whitelist:I suspect that it’s the newline that’s causing the error.
UPDATE:
I did a test on Windows and it’s indeed the carriage return (
\r) and line feed (\n) that cause the problem. I getErrno::EINVAL: Invalid argument.This should fix it, by removing all whitespace: