replace variable with its value in a ruby string, string itself is stored in a variable? -
i have variable containing string , in run time replace variables stored in string.
for example..
my_string = "congrats have joined groupname." groupname = "*name of group*" puts my_string
output:-
"congrats have joined *name of group*"
issue is:
my_string = " congrats have joined #{groupname}" expects groupname exists.. in case have define my_string before variable in it.
solution 1:
one way can be.. string replacment using gsub.. thats not one..
ps:
what trying achieve. have set of 100 messages have deliver. want define @ 1 single place , replace variable when needed. want define these variables(100 ones) in application_controller, can concatenate each variable(one of 100) defined. , automatically variable(variable defined in string stored in 1 of 100 variables). this language quite confusing.. check example explained above..
you store format string:
my_string = "congrats have joined %s" group_name = "my group" puts my_string % group_name # prints: congrats have joined group
for multiple variables in same string can use
my_string = "congrats have joined %s %s" group_name = ['group1', 'group2'] puts my_string % ['group1', 'group2']
will result:--
"congrats have joined group1 group2"
Comments
Post a Comment