Search code examples
rubyshellstring-interpolation

Ruby String interpolation in a shell execution


I am trying to make part of a program, that will create a folder with the current date as the foldername, the simplest way seems to be using string interpolation but that doesn't work and I'm not sure how to get the variable to be used

require 'date'
puts "Start"
datuh = DateTime.now
puts datuh
pid1 = Kernel.spawn('mkdir -p "#{datuh}"')
Process.wait pid1
puts "Finished"

the end goal is to make a folder with the current date, but it makes a folder with the name #{datuh} right now

Thanks


Solution

  • The issue is that you're using single quotes for the string. Single-quoted strings don't use interpolation. Here's something that works:

    require 'date'
    puts "Start"
    datuh = DateTime.now
    puts datuh
    pid1 = Kernel.spawn("mkdir -p \"#{datuh}\"")
    Process.wait pid1
    puts "Finished"
    

    More details here: https://ruby-for-beginners.rubymonstas.org/bonus/string_interpolation.html