Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace variable with its value in a ruby string, string itself is stored in a variable?

Tags:

string

ruby

I have a variable containing a string and in run time i was to replace some variables which are stored in that string.

for example..

 my_string = "Congrats you have joined groupName."
 groupName = "*Name of my group*"
  puts my_string

Output:-

 "Congrats you have joined *name of the group*"

issue is:

my_string = " Congrats you have joined #{groupName}" expects groupName already exists.. but in my case i have to define my_string before variable in it.

Solution 1:

One way can be.. string replacment like using gsub.. but thats not good one..

PS:

What I am trying to achieve. We have some set of 100 messages that we have to deliver. I want to define at one single place and just replace some variable when needed. Now i want to define all these variables(100 ones) in the application_controller, so that I can just concatenate each variable(one of 100) defined. And automatically variable(variable which is defined in the string stored in one of those 100 variables). This language is quite confusing.. Check the example i explained above..

like image 487
Mohit Jain Avatar asked Jul 21 '11 12:07

Mohit Jain


1 Answers

Or you can do this:

2.0.0-p247 :034 > a = "I love my live, says %{who}"
 => "I love my live, says %{who}" 
2.0.0-p247 :035 > a % { :who => "me" }
 => "I love my live, says me" 
like image 93
Nabheet Avatar answered Oct 12 '22 23:10

Nabheet