是否有Java MessageFormat的Ruby等价物?

时间:2015-03-19 07:25:13

标签: ruby messageformat

我有一个格式的字符串:

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?

Ruby是否有某种内置方法来执行此操作?还是有宝石?或者我必须只更换字符串?

编辑:我想补充一点,我不允许编辑这些字符串。因此,类似sprintf的解决方案不起作用。

4 个答案:

答案 0 :(得分: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 :(得分: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

希望有所帮助!

答案 2 :(得分: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?"

答案 3 :(得分:0)

made one,但由于Ruby不是我最强的套装,所以我们非常感谢任何改进。来源位于github