Search code examples
rubytiny-tds

Remove square brackets from array?


I have an array that I'm trying to load into a SQL statement. When I compile the SQL statement and include the array, it also puts the [] brackets into the string, and I need to remove them in order to insert it into my DB.

Here's my code:

i = 0

while i < rows.length
     sql = "INSERT INTO my_table VALUES(#{rows[i]})"
     puts sql
end

Current output:

INSERT INTO my_table VALUES(["value 1", "value 2", "value 3"])

Desired output:

INSERT INTO my_table VALUES("value 1", "value 2", "value 3")

Solution

  • Use inspect and join:

    sql = "INSERT INTO my_table VALUES(#{rows[i].map{|x| x.inspect}.join(', ')})"
    
    • map calls a block on each element of an array, then sets that element to the return value of the block
    • inspect turns a string into its representation (like "the string" (with quotation marks around it))
    • join puts them all together with a delimiter in between