【问题标题】:Group strings with similar pattern in Ruby在 Ruby 中对具有相似模式的字符串进行分组
【发布时间】:2011-09-03 17:22:45
【问题描述】:

我有一个文件名数组。其中的一个子集可能有类似这样的模式(字母字符串末尾有一个数字):

arr = %w[
  WordWord1.html
  WordWord3.html
  WordWord10.html
  WordWord11.html
  AnotherWord1.html
  AnotherWord2.html
  FileFile.html
]

如何识别相似的(它们具有相同的子字符串,只是它们的数字不同)并将它们移动到数组中?

['WordWord1.html', 'WordWord3.html', 'WordWord10.html', 'WordWord11.html']
['AnotherWord1.html', 'AnotherWord2.html']
['FileFile.html']

【问题讨论】:

    标签: arrays ruby string algorithm


    【解决方案1】:
    arr.group_by { |x| x[/[a-zA-Z]+/] }.values
    

    【讨论】:

    • group_by 是一个 ActionPack 插件,不一定对 OP 可用
    • 它包含在 ruby​​ 1.9 中,但我猜他可能还有旧版本。
    • 我使用的是 rbx-head,尽管它与 1.9 不兼容,但令人惊讶的是它确实有 group_by
    • @Ian:在 1.8.7 中也可以使用。
    【解决方案2】:
    arr = %w[
      WordWord1.html
      WordWord3.html
      WordWord10.html
      WordWord11.html
      AnotherWord1.html
      AnotherWord2.html
      FileFile.html
    ]
    
    result = {}
    
    arr.each do |a|
      prefix = a.match(/[A-Za-z]+/).to_s
      if result[prefix]
        result[prefix] << a
      else
        result[prefix] = [a]
      end
    end
    
    p result
    

    【讨论】:

      【解决方案3】:
      filenames = ["WordWord1.html", "WordWord3.html", "WordWord10.html", "WordWord11.html", "AnotherWord1.html", "AnotherWord2.html", "FileFile.html"]
      filenames.inject({}){|h,f|k = f.split(/[^a-zA-Z]/, 2).first;h[k] ||= [];h[k] << f; h}
      

      【讨论】:

        猜你喜欢
        • 2015-10-07
        • 2012-01-27
        • 1970-01-01
        • 2017-07-01
        • 2021-04-23
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多