5

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?

2

2 Answers 2

7

Use the % operator:

'database store string says: %{param}' % {param: 'noice'}
#=> "database store string says: noice"
Sign up to request clarification or add additional context in comments.

1 Comment

Note that the named reference starts with %, not #
0
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.