Wednesday, March 14, 2007

Shortening the code via string interpolation

The string interpolation operator gives you a way to drop variables, method return values, or anything else, into a string. This can save you a lot of back-and-forth between print and puts:
puts "This ticket is for: #{ticket.event}, at #{ticket.venue}."
puts "The perform is #{ticket.performer}."
puts "The seat is #{}, "
puts "and it costs $#{"%.2f." % ticket.price}"
Whatever’s inside the interpolation operator #{...} gets calculated separately, and the results of the calculation are pasted automatically into the string.
When you run these lines, you don’t see the #{...} operator on your screen; instead, you see the results of calculating or evaluating what was inside that operator.

No comments: