Using `gets` for file path

1

I'm writing a script to edit an excel file. I'm testing if it collects information from a user.

require 'rubygems'
require 'win32ole'

print "filpath?"
$filepath = $stdin.gets

print "sheet?"
$sheetname = $stdin.gets

excel = WIN32OLE.new('Excel.Application')
excel.visible = true
workbook = excel.workbooks.Open($filepath)
worksheet = workbook.Worksheets($sheetname)
worksheet.Cells(2,2).Value = 10
workbook.saved = true 
workbook.Save
excel.ActiveWorkbook.Close(0)
excel.Quit()

When I put my file path in the script directly, it works fine. It can look up the excel file and edit it normally. However, when I collect it from a gets statement, it gives me this error message:

test.rb:20:in `method_missing': (in OLE method `Open': ) (WIN32OLERuntimeError)
    OLE error code:800A03EC in Microsoft Excel
      Sorry, we couldn't find C:\filename.xlsx
. Is it possible it was moved, renamed or deleted?
    HRESULT error code:0x80020009
      Exception occurred.
        from test.rb:20:in `<main>'

Not sure what is happening. I would love any help.

ruby
asked on Stack Overflow Oct 1, 2015 by Anders • edited Oct 1, 2015 by sawa

1 Answer

4

The end line character is appended to the file name when you receive it with gets, but probably your file is not named as such. Add .chomp after gets. It is also better to check the existence and the accessibility of the file before passing it to win32ole.

answered on Stack Overflow Oct 1, 2015 by sawa

User contributions licensed under CC BY-SA 3.0