如何使用Ruby on Rails将字符串转换为数组
我有一个文本字段,它接受一个字符串值,如
"games,fun,sports"
我的主要目标是获取字符串并将其转换为如下所示的数组:
[games, fun, sports]
在我拥有的集成对象的filters属性中。 现在我有一个似乎不起作用的方法的开头。
这是我的代码:
视图:
:integrations, :action => :update, :id => @integrations.id) do |f| %>
这是接收字符串的文本字段。
模型:
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
所以,回顾一下:我有一个集成模型,它接受一串filter。 我想要一个方法,将字符串分解为filter属性的元素。
这是我正在尝试将filter添加到的对象:
宾语:
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\"]"
我想这个:
[Hey, ohh]
目前还不清楚你追求的是什么,但通常情况下,如果你有一个字符串:
"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"]
一种选择是使用JSON。
require 'json' filters = "[\"Hey\", \"ohh\"]" JSON.parse(filters)
收益:
["Hey","ohh"]
您需要删除多余的字符,然后使用拆分模式将字符串拆分为数组,如下所示:
"[\"Hey\", \"ohh\"]".gsub(/(\[\"|\"\])/, '').split('", "')
哪个回报:
["Hey", "ohh"]