简体   繁体   中英

Get & store digits from string

I have a string of values like this:

=> "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"

I want to put each value in an array so I can use each do. So something like this:

@numbers =>["72", "58", "49", "62", "9", "13", "17", "63"]

This is the code I want to use once the string is a usable array:

@numbers.each do |n| 
  @answers << Answer.find(n)
end

I have tried using split() but the characters are not balanced on each side of the number. I also was trying to use a regex split(/\\D/) but I think I am just getting worse ideas.

The controller:

@scores = []
  @each_answer = []
  @score.answer_ids.split('/').each do |a| 
    @each_answer << Answer.find(a).id
  end

Where @score.answer_ids is:

=> "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"

Looks like an array of JSON strings. You could probably use Ruby's built-in JSON library to parse it, then map the elements of the array to integers:

input = "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"

require 'json'
ids = JSON.parse(input).map(&:to_i)

@answers += Answer.find(ids)

I'd use:

foo = "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
foo.scan(/\d+/) # => ["3", "4", "60", "71", "49", "62", "9", "14", "17", "63"]

If you want integers instead of strings:

foo.scan(/\d+/).map(&:to_i) # => [3, 4, 60, 71, 49, 62, 9, 14, 17, 63]

If the data originates inside your system, and isn't the result of user input from the wilds of the Internet, then you can do something simple like:

bar = eval(foo) # => ["3", "4", "60", "71", "49", "62", "9", "14", "17", "63"]

which will execute the contents of the string as if it was Ruby code. You do NOT want to do that if the input came from user input that you haven't scrubbed.

In your code n is a String, not an Integer. The #find method expects an Integer, so you need to convert the String to an Array of Integers before iterating over it. For example:

str = "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
str.scan(/\d+/).map(&:to_i).each do |n|
    @answers << Answer.find(n)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM