1

次の形式の文字列があります。

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

array を指定する["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

0

は 1 つを作成しましたが、Ruby は私の最強のスーツではないので、改善があれば大歓迎です。ソースはgithubにあります。

于 2015-08-14T15:32:00.477 に答える
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
 "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 に答える