Search code examples
rubystringvariablespath

How to use a variable for a file path? Ruby


Is there the possibility in Ruby to use a variable / string to define a file path?

For example I would like to use the variable location as follow:

location = 'C:\Users\Private\Documents'

#### some code here ####
class Array
  def to_csv(csv_filename)
    require 'csv'
    CSV.open(csv_filename, "wb") do |csv|
      csv << first.keys # adds the attributes name on the first line
      self.each do |hash|
        csv << hash.values
      end
    end
  end
end

array = [{:color => "orange", :quantity => 3},
         {:color => "green", :quantity => 1}]

array.to_csv('location\FileName.csv')

Solution

  • You can use variable inside string, following way:

    array.to_csv("#{location}\FileName.csv")