Reputation: 5629
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?
Upvotes: 5
Views: 392
Reputation: 908
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?
Upvotes: 0
Reputation: 897
Use the %
operator:
'database store string says: %{param}' % {param: 'noice'}
#=> "database store string says: noice"
Upvotes: 7