Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby convert string array to array object [duplicate]

I want to import my CSV file to my database, my CSV file has following string and I need to parse it to a Ruby array object, how to do that?

"[\"Mt Roskill\", \"Sylvia Park\"]"

Thanks

like image 725
user1883793 Avatar asked May 10 '15 11:05

user1883793


People also ask

What does .select do in Ruby?

Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

How do I merge two arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).

What is .first in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

Can you split an array Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


1 Answers

That example string looks like JSON. Use JSON.parse to return a Ruby array:

require 'json'

JSON.parse("[\"Mt Roskill\", \"Sylvia Park\"]")
#=> ["Mt Roskill", "Sylvia Park"]
like image 101
spickermann Avatar answered Oct 11 '22 13:10

spickermann