Reputation: 1221
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
Reputation: 27822
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:
Upvotes: 11