1

我有一个格式的字符串:

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

4 回答 4

5

使用内核#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"]
于 2015-03-19T07:44:15.830 回答
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?"
于 2015-03-19T08:20:20.733 回答
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" }

在这里检查我的答案!

希望有帮助!

于 2015-03-19T07:28:34.857 回答
0

做了一个,但由于 Ruby 不是我最擅长的,任何改进都将不胜感激。源代码在github 上

于 2015-08-14T15:32:00.477 回答