Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to string with quotes

Tags:

ruby

How do I convert an array like:

[["hello"], ["world"]]

To:

"hello", "world"

I tried array.join(',')

But this would return:

"hello world"

What I want is a string with qoutes: ""hello", "world"".


For completeness:

I am trying to build this query from the array.

DELETE FROM table WHERE column IN ("hello", "world");
like image 640
majidarif Avatar asked Aug 31 '26 08:08

majidarif


2 Answers

Try:

array.map{|s| "\"#{s}\""}.join(', ')

Update:

With structure [['a'],['b'] do:

array.map{|s| "\"#{s.first}\""}.join(', ')
like image 117
BroiSatse Avatar answered Sep 02 '26 12:09

BroiSatse


I'd do like this:

array.map { |a| a.first.inspect }.join(', ')
# => "\"hello\", \"world\""

Update: a couple of alternative solutions:

array.flatten.map(&:inspect).join(', ')
# => "\"hello\", \"world\""

Using the String#quote method from Ruby Facets:

require 'facets/string/quote'
array.flatten.map(&:quote).join(', ')
# => "\"hello\", \"world\""
like image 45
toro2k Avatar answered Sep 02 '26 12:09

toro2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!