Home > Back-end >  How to use a variable for a file path? Ruby
How to use a variable for a file path? Ruby

Time:05-19

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')

CodePudding user response:

You can use variable inside string, following way:

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

CodePudding user response:

You can use File.join, which accepts variables as arguments.

irb(main):001:0> filename = File.basename('/home/gumby/work/ruby.rb')
=> "ruby.rb"
irb(main):002:0> path     = '/home/gumby/work'
=> "/home/gumby/work"
irb(main):003:0> File.join(path, filename)
=> "/home/gumby/work/ruby.rb"

As noted above, if you start embedding slashes in your strings things may get unmanageable in future.

  • Related