问题描述:

I'm working on a phrase generator project. I have a set of vocabulary, and a set of grammar. The "grammar" is just the template statement for which vocabulary will be inserted into. For instance:

The grammar could be: "For Christmas I got a _____!" and the blank would be replaced by a, previously define, randomly selected vocabulary term.

I want a fancier system than just inserting vocab into the string when asked to do so (because that's pretty easy to do).

I want to use a string such as: "For Christmas I got a {fcap(123)}!" Where the curly brackets define a place to insert a generated vocab term, and "fcap" is a method name that uses "123" as its parameters. In this case "fcap" capitalizes the first letter of the generated vocab term.

I'm using Ruby to quickly figure out how to do this in general, I plan on using C# in the final product. I've search many forums, including this one, and failed in all of my own experiments. I really don't even know what this sort of thing is called.

Lastly, I want to be able to do this will much flexibility, so I'd like to have nested methods, and multiple inserts of the curly brackets within the same string. For right now, I'm not gonna allow the vocab to have any functional curly braces to avoid infinite loops.

I'll take any help here, even if it's just pointing me to what/where I should research. Thanks in advanced!

网友答案:

Ruby string interpolation should be enough here:

"For Christmas I got a #{fcap(123)}!"

beween #{} you can put any ruby expression. It will be evaluated and the answer converted to string and interpolated in the big string.

相关阅读:
Top