mike
mike

Reputation: 365

How to split string into an array into two separate strings

I have the following Ruby on Rails params:

<ActionController::Parameters {"type"=>["abc, def"], "format"=>:json, "controller"=>"order", "action"=>"index"} permitted: false>

I want to check if there's a , in the string, then separate it into two strings like below and update type in params.

<ActionController::Parameters {"type"=>["abc", "def"], "format"=>:json, "controller"=>"order", "action"=>"index"} permitted: false>

I tried to do like below:

params[:type][0].split(",") #=> ["abc", " def"]

but I am not sure why there's a space before the second string.

How can I achieve that?

Upvotes: 0

Views: 1294

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33471

Because there's a whitespace in your string, that's why the result of using split will also include it in the splitted element for the array.

You could remove first the whitespaces and then use split. Or add ', ' as the split value in order it takes the comma and the space after it. Or depending on the result you're trying to get, to map the resulting elements in the array and remove the whitespaces there, like:

string = 'abc, def'
p string.split ','              # ["abc", " def"]
p string.split ', '             # ["abc", "def"]
p string.delete(' ').split ','  # ["abc", "def"]
p string.split(',').map &:strip # ["abc", "def"]

Upvotes: 1

Related Questions