Title: ruby: wrap each element of an array in additional quotes
Tags: ruby-on-rails;ruby
Question: 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)
=&gt; []
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)
=&gt; [#<Info mk1: "1222", mk2: "", pk1: "Information allgemein", pk2: "Geschlecht", pk3: "Wert", value_string: "männlich", value_number: nil&gt;]
So, I just need to wrap every element of names into additional ''-quotes.

Here is the accepted answer: names.map{ |e| "'" + e + "'" }
=&gt; ["'001'", "'Barbara'", "'122'"]
names.map{ |e| "'#{e}'" }
=&gt; ["'001'", "'Barbara'", "'122'"]

Here is another answer: 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 &amp;:inspect    # =&gt;  [&quot;\&quot;001\&quot;&quot;, &quot;\&quot;Barbara\&quot;&quot;, &quot;\&quot;122\&quot;&quot;]
If you are print this in your views, you should mark it as html safe:
names.map(&amp;:inspect).html_safe

Here is another answer: 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.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:05/16/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<ruby-on-rails><ruby>', 'Title': 'ruby: wrap each element of an array in additional quotes', 'ViewCount': 11286, 'id': 30276873, 'user_AboutMe': None, 'user_AccountId': 279438.0, 'user_DisplayName': 'Alina', 'user_Reputation': 2131.0, 'user_Views': 462.0, 'user_id': 574591.0}}