Search code examples
rubyclassstring-interpolation

String interpolation prints variable name instead of variable contents


I have a class like this:

class Example
    def printThisVar(printThing)
        print 'this is the var: #{printThing}'   
    end
end

However, the string that is printed is printed is "this is the var: #{printThing}" not "this is the var: exampleText".

Is there any way to fix this? thanks!


Solution

  • You have single quotes instead of double quotes around the string you want to print.

    class Example
        def print_this_var(print_thing)
            print 'this is the var: #{print_thing}'
        end
    end
    
    foo = Example.new
    foo.print_this_var("example_text")
    
    #=> this is the var: #{print_thing}
    

    Changing the method definition to

            print "this is the var: #{print_thing}"
    

    yields

    #=> this is the var: example_text
    

    String interpolation doesn't work with single quotes.