2015-03-19 41 views
1

我有格式的字符串:是否有与Java MessageFormat相当的Ruby?

Hello {0}, today is {1} and the time is {2}. Will you be eating {3}?

给予阵列["sir", "Monday", "12:00", "tacos"],该字符串应该被格式化为:

Hello sir, today is Monday and the time is 12:00. Will you be eating tacos?

确实红宝石有某种内置的方法做这个?还是有宝石?或者我必须更换字符串?

编辑:我想补充一点,我不允许编辑这些字符串。因此sprintf式的解决方案将无法工作。

回答

0

你可以做这样的事情:

message = "Hello %{tile}, today is %{day_name} and the time is %{time}. Will you be eating %{food}?" 

p message % { title: "sir", day_name: "Monday", time: "12:00", food: "tacos" } 

检查我的答案here

希望有帮助!

5

随着Kernel#sprintf

sprintf("Hello %s, today is %s and the time is %s. Will you be eating %s?", *["sir", "Monday", "12:00", "tacos"]) 

"Hello %s, today is %s and the time is %s. Will you be eating %s?" % ["sir", "Monday", "12:00", "tacos"] 
+1

您可以使用'%1 $ s','%2 $ s','%3 $ s'等特定参数。 – Stefan 2015-03-19 08:45:35

0
"Hello %s, today is %s and the time is %s. Will you be eating %s?" % ["sir", "Monday", "12:00", "tacos"] 
# => "Hello sir, today is Monday and the time is 12:00. Will you be eating tacos?" 
0

made one,但Ruby是不是我的最强的西装,任何改进,将不胜感激。来源是github

相关问题