Shan Sunny
Shan Sunny

Reputation: 102

Ruby Variable replacement inside another Variable

I have a ruby variable created from a complex code , But I am unable to replace the variable declared inside my main variable . Here is an example , it may be simple but I could not able to change main variable declaration procedure.

irb(main):065:0> p msg
"My name is \#{name}"
irb(main):066:0> puts name
Foo
irb(main):067:0> puts msg
My name is #{name}
irb(main):068:0> puts "#{msg}"
My name is #{name}

I want an output like "My name is Foo" ; That needs to be achieved considering I can't control content format of variable 'msg'

Upvotes: 1

Views: 165

Answers (2)

peter
peter

Reputation: 42207

You could build your own String class with a substitution at runtime.

class StringInterpollator < String
  def replace(bind)
    gsub(/\\*#\{(\w+)\}/) do |m|
      eval($1, bind)
    end
  end
end

msg = 'My name is \#{name}'
name = "Foo"

StringInterpollator.new(msg).replace binding #My name is Foo

EDIT: here a version that accepts both local variables as instance variables

class StringInterpollator < String
  def replace(bind)
    gsub(/\\*#\{?([\w@]+)\}?/){ |m| eval($1, bind)}
  end
end

Upvotes: 2

xplosiveFibonacci
xplosiveFibonacci

Reputation: 51

One simple approach is to use string substitution with the sub method like this

name = "Foo"
msg.sub('#{name}', name) # => "My name is Foo" 

However, this assumes that msg always contains the text \#{name}

Upvotes: 0

Related Questions