Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby apply string interpolation to a single-quote string

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?

like image 290
Qqwy Avatar asked Nov 19 '15 11:11

Qqwy


People also ask

How do you interpolate a string in Ruby?

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.

Can you use single quotes in Ruby?

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.

What's the difference between single quotes or double quotes when using string interpolation?

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.

What does #{} do in Ruby?

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 .


1 Answers

Use the % operator:

'database store string says: %{param}' % {param: 'noice'}
#=> "database store string says: noice"
like image 178
Damiano Stoffie Avatar answered Nov 15 '22 06:11

Damiano Stoffie