1

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

tokland
  • 66,169
  • 13
  • 144
  • 170
Mike
  • 13
  • 4
  • Note: your usage of `File.new` keeps filehandles open until the script exits. Not a big deal in a short-lived script though. – Kelvin Sep 07 '12 at 22:09

1 Answers1

0

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 line contains 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 line variable immediately before calling File.new to see what it contains.

You probably need to sanitize line by removing invalid characters. See this answer for what isn't allowed. The easy way would be to use a simple whitelist:

# remove non-alphanumeric and non-underscore
line.gsub!(/\W/, '')

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 get Errno::EINVAL: Invalid argument.

This should fix it, by removing all whitespace:

line.gsub!(/[\s]/, '')
Community
  • 1
  • 1
Kelvin
  • 20,119
  • 3
  • 60
  • 68