【问题标题】:Split a string in Ruby在 Ruby 中拆分字符串
【发布时间】:2013-05-29 17:03:49
【问题描述】:

我有一个在 ruby​​ 中返回给我的哈希

test_string = "{cat=6,bear=2,mouse=1,tiger=4}"

我需要以这种形式获取这些项目的列表,按数字排序。

animals = [cat, tiger, bear, mouse]

我的想法是在 ruby​​ 中对此进行处理,并在 '=' 字符上进行拆分。然后尝试订购它们并放入新列表。在红宝石中有一种简单的方法可以做到这一点吗?示例代码将不胜感激。

【问题讨论】:

  • 不清楚你在这里问什么。您的第一个代码块中的数据是作为哈希对象还是作为表示哈希对象的字符串?
  • 表示哈希对象的字符串。
  • stackoverflow.com/questions/1667630/… 也许这将有助于特别是关于拆分的答案?
  • 你不需要to_s它,它已经是一个字符串了。
  • 他不使用标准的Hash#to_srepresentation。没有哈希火箭。

标签: ruby


【解决方案1】:
s = "{cat=6,bear=2,mouse=1,tiger=4}"

a = s.scan(/(\w+)=(\d+)/)
p a.sort_by { |x| x[1].to_i }.reverse.map(&:first)

【讨论】:

    【解决方案2】:
     a = test_string.split('{')[1].split('}').first.split(',')
     # => ["cat=6", "bear=2", "mouse=1", "tiger=4"]
     a.map{|s| s.split('=')}.sort_by{|p| p[1].to_i}.reverse.map(&:first)
     # => ["cat", "tiger", "bear", "mouse"]
    

    【讨论】:

      【解决方案3】:

      这不是最优雅的方式,但它确实有效:

      test_string.gsub(/[{}]/, "").split(",").map {|x| x.split("=")}.sort_by {|x| x[1].to_i}.reverse.map {|x| x[0].strip}

      【讨论】:

        【解决方案4】:

        下面的代码应该可以做到。 解释了内联的步骤

        test_string.gsub!(/{|}/, "") # Remove the curly braces
        array = test_string.split(",") # Split on comma
        array1= [] 
        array.each {|word|
            array1<<word.split("=") # Create an array of arrays
        }
        h1 = Hash[*array1.flatten] # Convert Array into Hash
        puts h1.keys.sort {|a, b| h1[b] <=> h1[a]} # Print keys of the hash based on sorted values
        

        【讨论】:

          【解决方案5】:
          test_string = "{cat=6,bear=2,mouse=1,tiger=4}"
          Hash[*test_string.scan(/\w+/)].sort_by{|k,v| v.to_i }.map(&:first).reverse
          #=> ["cat", "tiger", "bear", "mouse"]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-08-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-25
            • 2013-11-18
            • 2011-04-29
            • 2021-10-30
            相关资源
            最近更新 更多