0

I have user controller input like so (the length and # of items may change):

str = "['honda', 'toyota', 'lexus']"

I would like to convert this into an array, but I'm struggling to find the best way to do so. eval() does exactly what I need, but it is not very elegant and is dangerous in this case, since it's user controller input.

Another way is:

str[1..-2].split(',').collect { |car| car.strip.tr("'", '') }

=> ["honda", "toyota", "lexus"]

But this is also not very elegant. Any suggestions that are more 'Rubyish'?

1
  • 2
    Could you provide some more context about why you're working with a string in this way? The cleanest solution to your problem is likely to change the input. Commented Apr 5, 2017 at 23:20

2 Answers 2

2

You could use a regular expression:

# match (in a non-greedy way) characters up to a comma or `]`
# capture each word as a group, and don't capture `,` or `]`
str.scan(/'(.+?)'(?:,|\])/).flatten

Or JSON.parse (but accounting for the fact that single quotes are in fact technically not allowed in JSON):

JSON.parse( str.tr("'", '"') )

JSON.parse probably has a small edge over the regexp in terms of performance, but if you're expecting your users to do single quote escaping, then that tr is going to mess things up. In this case, I'd stick with the regexp.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd strongly advocate the JSON.parse approach and steer away from that gnarly regular expression.
0

The JSON.parse looks more correct, but here is another alternative:

str.split(/[[:punct:] ]+/).drop(1)

Comments

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.