2

I am having some trouble writing a file to a specific path taking the file name from excel. Here is the code which I am using

out_file = File.new (@temp_path/ "#{obj_info[3].to_s}","w") 

"#{obj_info[3].to_s}" = sample.txt

The value sample.txt comes from Excel during run time

@temp_path = "C:/Users/Somefolder/"

The error displayed is:

NoMethodError: undefined method `[]' for nil:NilClass

However, if the code is:

out_file = File.new ("#{obj_info[3].to_s}","w")

it successfully creates a file called sample.txt in the default directory. However, I want it to be stored in a specific directory and the file name needs to be passed from Excel. Any help is much appreciated.

Justin Ko
  • 46,526
  • 5
  • 91
  • 101
TGR
  • 31
  • 4

2 Answers2

1

I believe your problem is because there a space between / and "

@temp_path/ "#{obj_info[3].to_s} 

and I guess you want to build a path.

My advice is that you use File.join

f_path = File.join(@temp_path,obj_info[3].to_s)
out_file = File.new (f_path,"w") 

Let me know if that solved the problem

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
0

You have 2 problems:

  1. obj_info is nil so you make an error reading the value from excel, the error you get indicates it is on an array, in the code you published the only thing that's an array is what you read from excel. Print the contents with p obj_info right before your code to check.

  2. @temp_path and {obj_info[3].to_s} need to be concatenated to make a path. You can do that with File.join like Mauricio suggests or like this

    out_file = File.new ("#{@temp_path}/#{obj_info[3]}","w")

You can drop the to_s in this case.

It would be better if you publish the whole of your script that is meaningful.

peter
  • 41,770
  • 5
  • 64
  • 108
  • Peter, thanks for the response. Infact your reply worked without the slash between temp_path and Obj_info. With the slash it gave me a syntax error SyntaxError: unexpected ')', expecting end-of-input. Currently, I am using the below and it works like a charm. **out_file = File.new ("#{@temp_path}#{obj_info[3]}","w")** – TGR May 22 '15 at 20:37
  • @TGR so you are using string interpolation when there is no part of the string that is fixed like ¨Hello #{user}". It never hurts to make the code more readable – Mauricio Gracia Gutierrez May 22 '15 at 21:09
  • Sure Mauricio. Will keep that in mind next time and thanks for your response as well. I am sure its going to help me as well. – TGR May 22 '15 at 21:37