Formatting your output - options available in Ruby
Archive - Originally posted on "The Horse's Mouth" - 2010-09-29 07:15:06 - Graham Ellis
1. Sending each of the expressions (be it a constant, a variable, or an expression) to the language's print function as a list of elements for the print statement to join up:
print("Henry is ",henry," and Jenny is ",jenny," and the difference is ",$diff,"\n")
2. Embedding the variables within the language's string construct using a syntax provided by the language for doing so:
puts("Henry is #{henry} and Jenny is #{jenny} and the difference is #{henry-jenny}")
3. Converting all of the values to be output into strings, then building up a complete string in an expression or variable which is outout:
puts("Henry is "+henry.to_s+" and Jenny is "+jenny.to_s+" and the difference is "+$diff.to_s)
4. Using a formatted printing function, with a single string to be output which includes placeholders, and additional parameters to fill in those placeholders:
printf("Henry is %d and Jenny is %d and the difference is %d\n",henry,jenny,$diff)
Of course, someone's going to ask "which one is best", and I'm going to say "it depends".
Option 1 - a whole list of things to output - is a very messy syntax with lots of "," to go wrong, and is hard to read. So it's not my favorite
Option 4 formats AND prints at the same time, and the computer science purists will tell you that a function should only do one thing at a time - so you'll be better to use an sprintf to do the formatting followed by a puts or print to do the output.
Option 3 is the way you'll find it done in languages such as Java - using an overloaded + operator to join strings, and a conversion method to convert numeric values into strings prior to joining them. It tends to be a bit verbose, but it's thorough - so longer to initially code and more straightforward to maintain.
Option 2 - where variables are embedded within a string - is the neatest. It's not available in all languages - in Ruby, you can see the syntax above. In Perl and PHP, where variables always start with a particular special character which the " operator understands (usually $, sometime @ in Perl), there's no need for the signatory #{..to..} as it's implicit in the variable name:
print("Henry is $henry and Jenny is $jenny and the difference is $diff\n");
There's a full example showing the options above [here]. And the sample output in each case looks like
Henry is 34 and Jenny is 21 and the difference is 13