我有一个格式的字符串:
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的解决方案不起作用。
答案 0 :(得分:5)
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)