Alina
Alina

Reputation: 2261

ruby: wrap each element of an array in additional quotes

I have a following string :

a = "001;Barbara;122"

I split in into array of strings:

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

What should I do to have each element wrapped additionally in '' quotes? The result should be

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

I know it sounds strange but I need it for database query in ruby on rails. For some reason I cannot access database record if my name is in "" quotes. I do have mk1==0006 in the database but rails does not want to access it somehow. However, it does access 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 every element of names into additional ''-quotes.

Upvotes: 6

Views: 12826

Answers (3)

Uzbekjon
Uzbekjon

Reputation: 11823

I agree with @jesenko that you should not construct your SQL queries and let AR do the type conversion and escape input against SQL injection attacts. However, there are other use cases when you'd want this. For example, when you want to insert an array of strings into your js. I prefer using the following syntax for those rare cases:

names.map &:inspect    # =>  ["\"001\"", "\"Barbara\"", "\"122\""]

If you are print this in your views, you should mark it as html safe:

names.map(&:inspect).html_safe

Upvotes: 0

jesenko
jesenko

Reputation: 1293

You should not concatenate parameters to sql string manually; you should instead pass parameters into find_by_sql method. 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 against sql injection will be handled by Rails.

Upvotes: 3

pangpang
pangpang

Reputation: 8831

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

or

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

Upvotes: 22

Related Questions