如何使用Ruby on Rails将字符串转换为数组

4

我有一个文本字段,可以输入字符串值,例如:

"games,fun,sports"

我的主要目标是将字符串转换为以下的数组:

[games, fun, sports]

在我的integrations对象的filters属性中,我有一段代码。目前我有一个似乎不起作用的方法开头。
这是我的代码:
视图:
  <%= form_for @integrations, url: url_for(:controller => :integrations, :action => :update, :id => @integrations.id) do |f| %>
   <%= f.label :filters %>
   <%= f.text_field :filters, class: "filter-autocomplete" %>
   <%= f.submit "Save" %>
  <% end %> 

那是接收字符串的文本字段。
模型:
def filters=(filters)

end

这是我希望从字符串转换为数组的位置。
控制器:
 def update
    @integrations = current_account.integrations.find(params[:id])

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

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

  private

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

所以,简单概括一下:我有一个集成模型,它接收一串过滤器字符串。我想要一个方法,将该字符串分解为过滤器属性的元素。
以下是我尝试添加过滤器的对象:
对象:
 id: "5729de33-befa-4f05-8033-b0acd5c4ee4b",
 user_id: nil,
 type: "Integration::Webhook",
 settings: {"hook_url"=>"https://hooks.zapier.com/hooks/catch/1062282/4b0h0daa/"},
 created_at: Mon, 29 Aug 2016 03:30:29 UTC +00:00,
 owner_id: "59d4357f-3210-4ddc-9cb9-3c758fc1ef3a",
 filters: "[\"Hey\", \"ohh\"]">

正如您所看到的,我正在尝试修改filters。而不是在对象中使用以下内容:

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

I would like this:

[Hey, ohh]

2
除非 gamesfunsportsHeyohh 是变量,否则 [games, fun, sports][Hey, ohh] 将是非法的数组定义。 - the Tin Man
3个回答

14

不清楚你具体需要什么,但一般情况下,当你有这样一个字符串:

"games,fun,sports"

您可以使用split(',')在逗号处将其拆分,并将其转换为字符串数组:
"games,fun,sports".split(',') # => ["games", "fun", "sports"]

如果您收到一个包含字符串的JSON编码数组,它看起来像:

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

也称为:

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

这可以很容易地返回为Ruby字符串数组:

require 'json'

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

Rails的to_json方法非常方便且始终存在。 - tadman
@tadman的to_json函数是将数组转换为字符串,但它的本意是相反的。 - Pere Joan Martorell

3

一种选择是使用JSON。

require 'json'
filters = "[\"Hey\", \"ohh\"]"
JSON.parse(filters)

返回:

["Hey","ohh"]

0
你需要去除额外的字符,然后使用分割模式将字符串拆分成数组,就像这样:
"[\"Hey\", \"ohh\"]".gsub(/(\[\"|\"\])/, '').split('", "')

这将返回:

["Hey", "ohh"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接