我有一个包含字符串的变量,在运行时我要替换存储在该字符串中的一些变量。
例如..
my_string = "Congrats you have joined groupName."
groupName = "*Name of my group*"
puts my_string
输出: -
"Congrats you have joined *name of the group*"
问题是:
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.
解决方案1:
一种方法可以是..字符串替换就像使用gsub ..但这不是一个好的..
PS:
我想要实现的目标。我们必须提供一些100条消息。我想在一个地方定义,只需在需要时替换一些变量。现在我想在application_controller中定义所有这些变量(100个),这样我就可以连接定义的每个变量(100个中的一个)。并自动变量(在存储在这100个变量之一中的字符串中定义的变量)。 这种语言令人困惑。查看我上面解释过的例子..
答案 0 :(得分:23)
或者你可以这样做:
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"
答案 1 :(得分:12)
您可以存储格式字符串:
my_string = "Congrats you have joined %s"
group_name = "My Group"
puts my_string % group_name # prints: Congrats you have joined My Group
对于同一字符串中的多个变量,您可以使用
my_string = "Congrats you have joined %s %s"
group_name = ['group1', 'group2']
puts my_string % ['group1', 'group2']
将导致: -
"Congrats you have joined group1 group2"
答案 2 :(得分:3)
您可以使用I18n功能替换变量:
I18n.backend.store_translations :en,
:congrats => 'Congrats you have joined %{group_name}!'
I18n.translate :congrats, :group_name => 'My Group'
# => 'Congrats you have joined My Group!'
这样,您只需要一个点来维护您的文本。您的application_controller
不是静态文本的最佳位置。
答案 3 :(得分:0)
my_string = "Congrats you have joined groupName."
groupName = "*Name of my group*"
puts my_string.gsub('groupName',groupName)
输出:
"Congrats you have joined *name of the group*"
它的作用是搜索'groupName'字符串并将其替换为groupName变量的内容
答案 4 :(得分:0)
您可以使用eval在运行时替换变量:
my_string = 'Congrats you have joined #{groupName}.'
groupName = "*Name of my group*"
puts eval('"'+ my_string +'"')