2015-03-19 78 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

相關問題