[英]Regular expression to match a simple logic of getting the proper digits from string
[英]Get & store digits from string
我有一串這樣的值:
=> "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
我想將每個值放在數組中,以便可以使用每個do。 所以像這樣:
@numbers =>["72", "58", "49", "62", "9", "13", "17", "63"]
一旦字符串是可用數組,這就是我要使用的代碼:
@numbers.each do |n|
@answers << Answer.find(n)
end
我試過使用split()
但是字符在數字的每一側都不平衡。 我也試圖使用正則表達式split(/\\D/)
但我想我的想法越來越糟。
控制器:
@scores = []
@each_answer = []
@score.answer_ids.split('/').each do |a|
@each_answer << Answer.find(a).id
end
其中@score.answer_ids
為:
=> "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
看起來像一個JSON字符串數組。 您可能可以使用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)
我會用:
foo = "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
foo.scan(/\d+/) # => ["3", "4", "60", "71", "49", "62", "9", "14", "17", "63"]
如果要整數而不是字符串:
foo.scan(/\d+/).map(&:to_i) # => [3, 4, 60, 71, 49, 62, 9, 14, 17, 63]
如果數據源自您的系統內部,而不是來自互聯網狂熱的用戶輸入的結果,那么您可以執行以下簡單操作:
bar = eval(foo) # => ["3", "4", "60", "71", "49", "62", "9", "14", "17", "63"]
它將執行字符串的內容,就像是Ruby代碼一樣。 如果輸入來自尚未擦洗的用戶輸入,則您不想這樣做。
在您的代碼中n是一個字符串,而不是整數。 #find方法需要一個整數,因此您需要在迭代之前將字符串轉換為整數數組。 例如:
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.