Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the slickest way to create a comma-separated string of n instances of character c?

Tags:

sql

groovy

In SQL statements, we often need to create a list of question marks that serve as parameters in an IN clause. What's the shortest GROOVY expression to duplicate a question mark (or any character) n times and join them with commas to form a string?

Example: expr('?', 3) would return "?,?,?"

like image 543
Jim Norman Avatar asked Dec 28 '22 08:12

Jim Norman


1 Answers

I don't know if the slickest, but I like this:

assert (['?'] * 3).join(',') == '?,?,?'

The * n operation on a list returns a list equal to that list concatenated n times, so ['?'] * 3 equals ['?', '?', '?']. Then the .join(',') just joins the elements of that list with a comma.

like image 125
epidemian Avatar answered Mar 23 '23 01:03

epidemian