How do I know when to use " print X " or " print "#{X}" "?


Replace this line with your code.


@lo26, try to compare in a bit more waste examples.
If you wish to include a variable (which is an object in Ruby) for printing your strings, you will type something rather like this (correct and very DRY):
print "Let's talk about #{my_object}." # :relaxed:

print "Let's talk about my_object." # :skull_crossbones:

On the other hand, the second correct way (but more messy, less DRY that executes more bits):
print "Let's talk about " my_object "." # :nerd:


So, either is correct, it is a choice. BUT, #{X} is preferred for all occasions? Would that be a reasonable conclusion?


1. If you were a programming language creator whose goal is to give the simplest opportunity to print to console coplex strings includding different objects, would you like to create a special syntaxes for this exact rule? That is maybe one of the reasons why #{} exists in Ruby? Everything you put between the { (left-bracket) and } (right-bracket) characters Ruby will run as the result there instead of those characters.
2. It make even more of sense when you will insert Ruby's computations into text strings, something like this:
print "What is 2 + 5? #{2+5}"
In console:
"What is 2 + 5? 7
3. Or even more exciting that you will learn further:
print"It's #{ > 12 ? - 12 :}:#{} #{ > 12 ? 'PM' : 'AM'} (GMT)"
In console:
It's 2:54 PM (GMT)
4. Per contra, just enjoy & feel free as you decide to jump to the most open community in the world (where every coder has his own style, thanks to modern syntax that is rather elastic).


Thanks cherrychoco, I think I need to concentrate my efforts less on what is "correct" and focus more on what issue I am trying to solve and code to that!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.