Ruby: wrap each array element in extra quotes

I have the following line:

a = "001;Barbara;122"

      

I split into an array of strings:

names = a.split(";")
names = ["001", "Barbara", "122"] 

      

What should I do so that each item is added additionally with `` quotes? The result should be

names = ["'001'", "'Barbara'", "'122'"]

      

I know this sounds strange, but I need this to query the database in ruby ​​on rails. For some reason, I cannot access the database record if my name is in quotes. I have mk1 == 0006 in the database, but rails don't want to access it in any way. However, he has access to 1222.

sql = "SELECT mk1, mk2, pk1, pk2, pk3, value_string, value_number FROM infos WHERE mk1 in (0006) AND value_string ='männlich';"         
recs = ClinicdbInfo.find_by_sql(sql)     
=> [] 

sql = "SELECT mk1, mk2, pk1, pk2, pk3, value_string, value_number FROM infos WHERE mk1 in (1222) AND value_string ='männlich';"         
recs = ClinicdbInfo.find_by_sql(sql)     
 => [#<Info mk1: "1222", mk2: "", pk1: "Information allgemein", pk2: "Geschlecht", pk3: "Wert", value_string: "männlich", value_number: nil>] 

      

So, I just need to wrap each name element in additional '' -quotes.

+3


source to share


2 answers


names.map{ |e| "'" + e + "'" }
=> ["'001'", "'Barbara'", "'122'"]

      

or



names.map{ |e| "'#{e}'" }
=> ["'001'", "'Barbara'", "'122'"]

      

+12


source


You don't have to concatenate parameters for the sql string manually; instead, you must pass parameters to the method find_by_sql

. Example:

sql = "SELECT mk1, mk2, pk1, pk2, pk3, value_string, value_number FROM infos WHERE mk1 in (?) AND value_string = ?"         
recs = ClinicdbInfo.find_by_sql [sql, 1222, "männlich"]

      



This way, the necessary type conversions and escaping to prevent sql injection will be handled by Rails.

+3


source







All Articles