randy newfield
randy newfield

Reputation: 1221

Joining array of strings into a quoted comma-separated list

If I have a array of strings like so:

arr = ["one", "two", "three"]

How would I convert it into a backtick-quoted comma-separated string like so:

"`one`, `two`, `three`"

I have accomplished it using three calls like so:

arr = arr.join "`, `"
arr = arr.prepend "`"
arr = arr += "`"

but I was wondering if there was a cleaner way to achieve this or if there was a better function to use besides join. Preferably a one liner.

Upvotes: 2

Views: 4902

Answers (1)

Martin Tournoij
Martin Tournoij

Reputation: 27822

I would use map and join:

arr = ["one", "two", "three"]

arr
  .map { |e| "`#{e}`" }
  .join(', ')

You could even put it on a single line:

arr.map { |e| "`#{e}`" }.join(', ')

Now, I'm not entirely sure of this, but it looks like you might be using this to perhaps quote parameters for an SQL query? If you are, then please don't do it like this, but use a proper SQL escaping function or parameterized queries.


In response to the confirmation that you're using this for an SQL query, a better way would be to use (assuming you're using sqlite3-ruby):

db = SQLite3::Database.new 'my_database.sqlite3'
arr = ["one", "two", "three"]

db.execute('select * from foo where a=? and b=? and c=?', arr) do |row|
  p row
end

This will make sure it always works. Adding backticks may seem like a good idea at first, but:

  • There are ways to work around this and do an SQL injection attack. This is bad and allows anyone to read or destroy data.
  • Even if it's just for personal use, it's good to do it the "proper way", since sooner or later you'll run into the problem that your data has a ` or some other special character you didn't think of, at which point your program breaks.

Upvotes: 11

Related Questions