Ruby applies string interpolation to a single quote string

I have a line containing some interpolated statements, for example description='Hello! I am #{self.name}'. This string is stored as-is in the database; therefore, without the use of automatic string interpolation.

I want to apply this interpolation later. I could do something crazy like eval("\"+description+\""), but there should be a more convenient, more ruby ​​way to do this, right?

+4
source share
2 answers

Use the operator %:

'database store string says: %{param}' % {param: 'noice'}
#=> "database store string says: noice"
+6
source
class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def description
    'Hello! I am #{self.name}'
  end

  def interpolated_description
    description.split('#').map { |v| v.match(/\{(.*)\}/) ? send($1.split('.').last) : v  }.join
  end
end

p = Person.new('Bot')

p.interpolated_description
=> "Hello! I am Bot"

How about this?

+1
source

Source: https://habr.com/ru/post/1616529/


All Articles