如何从下面两个下划线之间的数组值中提取特定数字

names = [ "create_sales_3920_7873","create_sales_49204_7873","create_sales_392_7873"]

如何从上面的数组中获得输出结果3920、49204、392

任何帮助都是可以理解的.

推荐答案

如果实际的names数组很长,我相信有一种更好的方法可以做到这一点,但是循环遍历数组并使用split将完成您所发布的示例的工作:

names = [ "create_sales_3920_7873","create_sales_49204_7873","create_sales_392_7873"]


# initialize empty results array
output = []

# iterate over each string in array
names.each do |name|
  # use split to grab substring and add to results array
 output << name.split(/create_sales_/).last.split(/_/).first
end

#confirm result => ["3920", "49204", "392"]
puts output

Ruby-on-rails相关问答推荐

RubyOnRail在测试环境中启动失败

会话控制器中的某种问题

nginx 中的 Rails 7 Active Storage - 图像中途停止加载 net::ERR_HTTP2_PROTOCOL_ERROR 200

从 rails 5 迁移到 rails 6

在 Rails 中进行 Http 基本身份验证

设计 token_authenticable 已弃用,有什么替代方案?

Rails 5:如何从数据库中删除列?

attr_accessible(*attributes) 和 attr_protected(*attributes) 有什么区别?

将 Amazon SES 与 Rails ActionMailer 结合使用

如何找出现有 Rails 应用程序基于哪个 Rails 版本?

如何在 Rails 中验证日期以使其在今天之后?

如何拯救 OmniAuth::Strategies::OAuth2::CallbackError?

在范围内传递参数

Ruby on Rails:如何为 postgresql 编辑 database.yml?

Rails,Docker:主机不存在:默认

如何翻译 ActiveRecord 模型类名称?

为什么不对 Rspec + Selenium 使用共享的 ActiveRecord 连接?

ActiveModel::MissingAttributeError:无法使用 FactoryGirl 写入未知属性ad_id

在任何来源中都找不到 thread_safe-0.3.0

将数组传递到 hidden_​​field ROR