Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Eddi Gonzalez
Eddi Gonzalez
2,174 Points

interpolation in file.open method

Hi, how do I interpolate a variable inside file.open method

I have somethink like open('C:\Users\Usuario\Documents\Unificada\Salida\something.txt', 'w') do |f|

and I would like to interpolate something.txt inside the method

BR

EG

Rainy Day
Rainy Day
2,515 Points

If you use double quotes around the first method argument, you can then interpolate variables into the string. See below for an example

#!/usr/bin/env ruby
some_variable = "MyCustomFile.txt"

File.open(File.expand_path("C:\Users/Usuario\Documents\Unificada\Salida\#{some_variable}"), 'w') do |f|
    # This will open the file at C:\Users/Usuario\Documents\Unificada\Salida\myCustomFile.txt
end

1 Answer

James Nobles
James Nobles
8,884 Points

I think you may have to concatenate. Something like "C://some/file/path" . "filename-variable.txt". Or construct the path in one method and then pass it to a file open method as an argument.

I found this on the web, "Paths aren't Strings" which would indicate the string based interpolation will not work. https://robm.me.uk/ruby/2014/01/18/pathname.html