Perl/Ruby string interpolation

A

Aiden Humphreys

How do I do this

String str =
"Excpetion due to " + reason + " , caused by " + cause;

using Perl like string interploation, like this:

String str =
interpolate("Exception due to $reason , caused by $cause", map);

is there a Perl/Ruby like interploate method in any popular Java API. I saw
mention of one in Commons lang but couldn't find it in the current relase.
Pretty easy to code one, I know, but why reinvent ...

A
 
R

Ross Bamford

How do I do this

String str =
"Excpetion due to " + reason + " , caused by " + cause;

using Perl like string interploation, like this:

String str =
interpolate("Exception due to $reason , caused by $cause", map);

is there a Perl/Ruby like interploate method in any popular Java API. I saw
mention of one in Commons lang but couldn't find it in the current relase.
Pretty easy to code one, I know, but why reinvent ...

A

Commons EL does it, but does lots more too. Also Velocity, but does
*lots* more too.

Groovy can do it too, so you could always write that particular class in
Groovy and compile it... (or at least use their interpolation API) :)
 
T

Tor Iver Wilhelmsen

Aiden Humphreys said:
is there a Perl/Ruby like interploate method in any popular Java
API. I saw mention of one in Commons lang but couldn't find it in
the current relase.

If you can use ordering instead of naming, java.text.MessageFormat
might serve your needs.
 
A

Alan Krueger

Tor said:
If you can use ordering instead of naming, java.text.MessageFormat
might serve your needs.

Unspoken in that condition is whether you plan to support multiple
languages in your message formatting. Trying to order everything the
same when translated into other languages is a nightmare.
 
T

Tor Iver Wilhelmsen

Alan Krueger said:
Unspoken in that condition is whether you plan to support multiple
languages in your message formatting. Trying to order everything the
same when translated into other languages is a nightmare.

No, just use e.g. "The file {$0} is {$1,number} bytes long" for
English and "{$1,number} bytes long the file {$0} is" in Yoda. See?
You don't order it in the string, the order is contextual, e.g. first
element here - $0 - is the filename and the second - $1 - is the size,
no matter where they appear in the message-format string.

The differenc is you cannot give names like in the map-using case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top