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
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.
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).
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.
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With