Convert String into Array in Rails

Convert string into Array in rails

Perhaps this?

   s.tr('[]', '').split(',').map(&:to_i)

How to convert a string to an array using Ruby on Rails

It's not clear what you're after, but generally, when you have a string like:

"games,fun,sports"

you can use split(',') to break it on the commas and turn it into an array of strings:

"games,fun,sports".split(',') # => ["games", "fun", "sports"]

If you're receiving a JSON encoded array of strings, it'll look like:

'["games", "fun", "sports"]'

AKA:

'["games", "fun", "sports"]' # => "[\"games\", \"fun\", \"sports\"]"

which can be returned to a Ruby array of strings easily enough:

require 'json'

JSON['["games", "fun", "sports"]'] # => ["games", "fun", "sports"]

Convert string to array in Ruby on rails

A JSON parser ought to work fine:

require "json"

str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
p JSON.parse(str)
# => [[591, 184], [741, 910], [987,512], [2974, 174]]

Try it on eval.in: https://eval.in/777054

How to convert a string to an array in Ruby

You can use json to convert it to an array.

class T
require 'json'
def array_detect(array_string)
begin
json = JSON.parse array_string
if json.is_a? Array
# is an array
else
# not an array
end
rescue JSON::ParserError => e
puts e.message
# not a valid json string
end
end
end

Convert array of strings to an array of integers

To convert a string to number you have the to_i method.

To convert an array of strings you need to go through the array items and apply to_i on them. You can achieve that with map or map! methods:

> ["", "22", "14", "18"].map(&:to_i)
# Result: [0, 22, 14, 18]

Since don't want the 0 - just as @Sebastian Palma said in the comment, you will need to use an extra operation to remove the empty strings: (The following is his answer! Vote for his comment instead :D)

> ["", "22", "14", "18"].reject(&:empty?).map(&:to_i)
# Result: [22, 14, 18]

the difference between map and map! is that map will return a new array, while map! will change the original array.

How do I convert a string to an array with spaces preserved in Ruby?


Use String#scan Instead of String#split

You don't want to use String#split because that won't preserve your spaces. You want to use String#scan or String#partition instead. Using Unicode character properties, you can scan for matches with:

'Hello   world!'.scan /[\p{Alnum}\p{Punct}]+|\p{Space}+/
#=> ["Hello", " ", "world!"]

You can also use POSIX character classes (pronounced "bracket expressions" in Ruby) to do the same thing if you prefer. For example:

'Hello   world!'.scan /[[:alnum:][:punct:]]+|[[:space:]]+/
#=> ["Hello", " ", "world!"]

Either of these options will be more robust than solutions that rely on ASCII-only characters or literal whitespace atoms, but if you know your strings won't include other types of characters or encodings then those solutions will work too.

Using Metacharacters for Brevity, Cautiously

If you're looking for brevity in your regular expression, and you're sure you won't need to concern yourself with Unicode characters or explicitly differentiating between non-whitespace characters and punctuation, you can also use the \s and \S metacharacters. For example:

'Hello   world!'.scan /\s+|\S+/
#=> ["Hello", " ", "world!"]

This is generally less robust than the character properties or bracket expressions above, but is still unambiguous, short, and easy to read. It fits your example, so it's worth mentioning, but the \S metacharacter can match control characters and other unexpected things, so you need to be cautious with it unless you really know your data. For example, your string might contain an invisible NUL or a control character like CTRL-D, in which case \S would catch it and return a Unicode-escaped character:

"\x00".scan /\S+/
#=> ["\u0000"]

?\C-D.scan /\S+/
#=> ["\u0004"]

This is probably not what you'd expect, but given a larger data set this type of thing inevitably happens. The more explicit you can be, the fewer problems you're likely to have with your production data.

Using String#partition

For the very simple use case in your original example, you only have two words separated by whitespace. That means you can also use String#partition to partition on the sequential whitespace. That will split the string into exactly three elements, preserving the whitespace that partitions the words. For example:

'Hello   world!'.partition /\s+/
#=> ["Hello", " ", "world!"]

While simpler, the partitioning approach won't work as well with longer strings such as:

'Goodbye   cruel world!'.partition /\s+/
#=> ["Goodbye", " ", "cruel world!"]

so String#scan is going to be a better and more flexible approach for the general use case. However, anytime you want to split a string into three elements, or to preserve the partitioning element itself, #partition can be very handy.

Ruby converting string to array of arrays

You could split your string like this:

string = "John Clark\nDallas\nSystem Engineer\nGlobal Edge\nWage 2\nY\n1\nRobin James\nCleveland\nArchitect\nMaxSys\nWage 3\nY\n0\nJoseph Neils\nLittle Rock\nDB Admin\nTech Sys\nWage 2\nY\n1\n"

string.split("\n").each_slice(7).to_a
#=> [["John Clark", "Dallas", "System Engineer", "Global Edge", "Wage 2", "Y", "1"], ["Robin James", "Cleveland", "Architect", "MaxSys", "Wage 3", "Y", "0"], ["Joseph Neils", "Little Rock", "DB Admin", "Tech Sys", "Wage 2", "Y", "1"]]

How to convert string into Array

If you know that the string contains an array, you can just plain use eval;

arr = eval(str)

If you're not sure, you can go for the a bit more involved removing braces, splitting on , and collecting the numbers to an array;

arr = str[1..-2].split(',').collect! {|n| n.to_i}

Demo of both here.



Related Topics



Leave a reply



Submit