Section 2.22. Delayed Interpolation of Strings


2.21. Embedding Expressions Within Strings

The #{} notation makes this easy. We need not worry about converting, appending, and concatenating; we can interpolate a variable value or other expression at any point in a string:

puts "#{temp_f} Fahrenheit is #{temp_c} Celsius" puts "The discriminant has the value #{b*b - 4*a*c}." puts "#{word} is #{word.reverse} spelled backward."


Bear in mind that full statements can also be used inside the braces. The last evaluated expression will be the one returned.

str = "The answer is #{ def factorial(n)                           n==0 ? 1 : n*factorial(n-1)                         end                         answer = factorial(3) * 7}, of course." # The answer is 42, of course.


There are some shortcuts for global, class, and instance variables, in which case the braces can be dispensed with:

print "$gvar = #$gvar and ivar = #@ivar."


Note that this technique is not applicable for single-quoted strings (because their contents are not expanded), but it does work for double-quoted here-documents and regular expressions.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net