0

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!

5
  • Are you sure this is the case? I tested your code with Example.new.printThisVar("exampleText\n") and it behaved as expected. Commented Jan 13, 2014 at 16:53
  • Running your code in ruby 2.0 and 1.8 worked fine for me. Perhaps print is being overloaded somewhere in your code. Have you tried using puts instead of print? Commented Jan 13, 2014 at 17:02
  • @Max yeah - it's weird I just figured out that it doesn't work when I save it to a file and run via Terminal I get that error... But if I do it via irb, then I don't... Commented Jan 13, 2014 at 17:12
  • @Max I guess I switched from '' to "" subconsciously - thanks though Commented Jan 13, 2014 at 17:15
  • @Matt I guess I switched from '' to "" subconsciously - thanks though Commented Jan 13, 2014 at 17:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks - is there a reason you need "" compared to ''?
@user22138 only double-quote strings allow interpolation, see Ruby Literals - Strings

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.