-5

I have a string looks like an array "[12,34,35,231]" But this is just a string contains square brackets at the begin and the end of it.

I need to separate strings looks like arrays and others.

To do this I want to convert a string to an array '12','34','35','231' and after conversion use it with the condition like this:

if array.is_a? Array
...
else
...
end

Could enybody tell me how to do that conversion in the right way?

4
  • 2
    string[1..-2].split(',') Commented Jan 11, 2018 at 11:12
  • 3
    Possible duplicate of Convert string into Array in rails Commented Jan 11, 2018 at 11:47
  • Where does that string come from? Commented Jan 11, 2018 at 12:48
  • @SagarPandya Yes, you are right, it duplicates that link. Thank you, and everyone for answers. I would like to remove my question, but I can't do it by technical reason. Commented Jan 11, 2018 at 14:03

4 Answers 4

6

It is not conversion, it is parsing.

The input string looks like JSON. If it is JSON then use the JSON Ruby module to decode it:

require 'json'
arr = JSON.parse("[12,34,35,231]")

arr is an array of numbers:

p arr
# [12, 34, 35, 231]

If you need the values as strings you can use method to_s to convert them to strings:

arr = arr.map(&:to_s)
p arr
# ["12", "34", "35", "231"]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1
str = "[12,34,35,231]"

str.split(/\D+/).reject(&:empty?)
 => ["12", "34", "35", "231"]

# If you want the elements as numbers instead of strings, do:
str.split(/\D+/).reject(&:empty?).map(&:to_i)
 => [12, 34, 35, 231]

1 Comment

While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
1
"[12,34,35,231]"[1...-1].split(',')

2 Comments

each(&:to_s) makes no difference.
@SagarPandya right. My mistake, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.