0

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?

1
  • Just strip the array - params[:type][0].split(",").compact.collect(&:strip) Commented Nov 20, 2017 at 20:47

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

3 Comments

delete(' ') will remove all space characters from the string, not just the extra whitespace. p string.split(",").map(&:strip) would be a better option, though split(', ') is the best case scenario if it's possible to use.
@Sebastian Palma. Thanks. I just realized what if i have 3 values e.g ["abc, def, ""], last one is a blank value. can i also separate it. i tried but it gives me ["abc", "def", "\"\""]
You could use string.split(', '), string.delete(' ').split(',') or to reject the empty values in the array string.split(',').map(&:strip).reject &:empty?.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.