I have a string that contains some interpolated statements, like description='Hello! I am #{self.name}'
. This string is stored as-is in the database; so without the automatic string interpolation applied.
I want to apply this interpolation at a later date. I could do something crazy like eval("\"+description+\"")
but there has to be a nicer, more ruby-esque way to do this, right?
Using String Interpolation "My name is " + my_name + "!" You can do this: "My name is #{my_name}!" Instead of terminating the string and using the + operator, you enclose the variable with the #{} syntax.
Single-quoted and double-quoted strings are (almost) equivalent in Ruby. Of course, you have to escape \' inside single-quoted strings and \" inside double-quoted strings.
The difference The essential difference between the two literal forms of strings (single or double quotes) is that double quotes allow for escape sequences while single quotes do not! A string literal created by single quotes does not support string interpollation and does not escape sequences.
You use it to represent a variable you want to print or puts out. For example: puts "#{var}" would puts out the value stored within your variable var .
Use the %
operator:
'database store string says: %{param}' % {param: 'noice'}
#=> "database store string says: noice"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With