0

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')
1
  • Learn about string interpolation. Aside from this, the String class has a method + for concatinating strings. You can do something like location+'\FileName.csv'. Side note: I suggest that you use forward slashes instead of backslashes as a path separator. Sooner or later, the backslashes will bite you if you use them inside a double-quoted string and you forget to escape them. Commented May 19, 2022 at 6:28

2 Answers 2

2

You can use variable inside string, following way:

array.to_csv("#{location}\FileName.csv")
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.