简体   繁体   English

从字符串获取并存储数字

[英]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. 我想将每个值放在数组中,以便可以使用每个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. 我试过使用split()但是字符在数字的每一侧都不平衡。 I also was trying to use a regex split(/\\D/) but I think I am just getting worse ideas. 我也试图使用正则表达式split(/\\D/)但我想我的想法越来越糟。

The controller: 控制器:

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

Where @score.answer_ids is: 其中@score.answer_ids为:

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

Looks like an array of JSON strings. 看起来像一个JSON字符串数组。 You could probably use Ruby's built-in JSON library to parse it, then map the elements of the array to integers: 您可能可以使用Ruby的内置JSON库进行解析,然后将数组的元素映射为整数:

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. 它将执行字符串的内容,就像是Ruby代码一样。 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. 在您的代码中n是一个字符串,而不是整数。 The #find method expects an Integer, so you need to convert the String to an Array of Integers before iterating over it. #find方法需要一个整数,因此您需要在迭代之前将字符串转换为整数数组。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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