lipenco
lipenco

Reputation: 1368

how to add quotes to all elements in the array

my ruby code in rails:

 WebFontConfig = {
          google: { families: [<%= @text %>] }
        }

gives me the outcome like this:

 WebFontConfig = {
          google: { families: [Aclonica,Aclonica,Acme,Acme,Aclonica] }
        }

But I need outcome like this:

  WebFontConfig = {
              google: { families: ['Aclonica','Acme'] }
            }

So I need ad ' around words and take only unique recored. How should I do it?

Upvotes: 1

Views: 649

Answers (2)

user1908597
user1908597

Reputation:

Here's a method you could use to do that.

input = "Aclonica,Aclonica,Acme,Acme,Aclonica"

def format(text_string = "")
  text_string
    .split(",")
    .uniq
    .map { |string| "'" + string + "'" }
    .join(", ")
end

format(input) #=> "'Aclonica', 'Acme'"

Upvotes: 1

Alex
Alex

Reputation: 641

I guess this sample is erb template.

And @text has defined in controller like as @text = 'Aclonica,Aclonica,Acme,Acme,Aclonica'

In this case, you can use next simple regexp:

WebFontConfig = {
  google: { families: [<%= @text.split(',').uniq.join(',').gsub(/[^,]+/, "'\\0'").html_safe %>] }
}

Upvotes: 1

Related Questions