Cameron Bass Cameron Bass - 1 year ago 105
Ruby Question

How to convert a string to an array using Ruby on Rails

I have a text field that takes in a string value, like


My main goal here is to take the string and turn it into a Array like this:

[games, fun, sports]

in the filters attribute for the integrations object I have. Right now I have the beginning of a method that doesn't seem to work.

Here is my code:


<%= form_for @integrations, url: url_for(:controller => :integrations, :action => :update, :id => do |f| %>
<%= f.label :filters %>
<%= f.text_field :filters, class: "filter-autocomplete" %>
<%= f.submit "Save" %>
<% end %>

That is the text field that takes in the string.


def filters=(filters)


This is the place that I'd like to make the switch from string to array.


def update
@integrations = current_account.integrations.find(params[:id])

if @integrations.update_attributes(update_params)
flash[:success] = "Filters added"
redirect_to account_integrations_path
render :filters

def filters
@integrations = current_account.integrations.find(params[:id])


def update_params
[:integration_webhook, :integration_pager_duty, :integration_slack].each do |model|
return params.require(model).permit(:filters) if params.has_key?(model)

So, recap: I have a integrations model that takes in a string of filters. I want a method that will break up the string into an element of filter attributes.

Here is the object that I'm trying to add the filters to:


id: "5729de33-befa-4f05-8033-b0acd5c4ee4b",
user_id: nil,
type: "Integration::Webhook",
settings: {"hook_url"=>""},
created_at: Mon, 29 Aug 2016 03:30:29 UTC +00:00,
owner_id: "59d4357f-3210-4ddc-9cb9-3c758fc1ef3a",
filters: "[\"Hey\", \"ohh\"]">

As you can see the
is what I'm trying to modify. Instead of this in the object:

"[\"Hey\", \"ohh\"]"

I would like this:

[Hey, ohh]

Answer Source

It's not clear what you're after, but generally, when you have a string like:


you can use split(',') to break it on the commas and turn it into an array of strings:

"games,fun,sports".split(',') # => ["games", "fun", "sports"]

If you're receiving a JSON encoded array of strings, it'll look like:

'["games", "fun", "sports"]'


'["games", "fun", "sports"]' # => "[\"games\", \"fun\", \"sports\"]"

which can be returned to a Ruby array of strings easily enough:

require 'json'

JSON['["games", "fun", "sports"]'] # => ["games", "fun", "sports"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download