如何将数字从字符串中提取到单独的数组中

时间:2017-03-28 20:21:39

标签: ruby-on-rails ruby

鉴于此字符串

"In 2015, I want to know how much does iPhone 6+ cost?"

我该如何返回[2015, 6]

我的第一次尝试是

numbers = str.tr("^0-9", '')

但是会产生20156

2 个答案:

答案 0 :(得分:8)

您可以使用scan

numbers = str.scan(/\d+/)
# => ["2015", "6"]

答案 1 :(得分:1)

scan更好,但这也有效。

"In 2015, I want to know how much does iPhone 6+ cost?".gsub(/\D/,' ').split
  #=> ["2015", "6"]