【问题标题】:How do I create a histogram by iterating over an array in Ruby如何通过迭代 Ruby 中的数组来创建直方图
【发布时间】:2014-02-18 22:08:31
【问题描述】:

所以我被告知要重写这个问题并概述我的目标。他们要求我迭代数组并“使用 .each 迭代频率并将每个单词及其频率打印到控制台......在单词和它的频率之间放置一个空格以提高可读性。”

puts "Type something profound please"
text = gets.chomp
words = text.split

frequencies = Hash.new 0
frequencies = frequencies.sort_by {|x,y| y}
words.each {|word| frequencies[word] += 1}
frequencies = frequencies.sort_by{|x,y| y}.reverse
puts word +" " + frequencies.to_s
frequencies.each do |word, frequencies|   

end

为什么它不能将字符串转换为整数?我做错了什么?

【问题讨论】:

    标签: ruby arrays histogram


    【解决方案1】:

    试试这个代码:

    puts "Type something profound please"
    words = gets.chomp.split #No need for the test variable
    
    frequencies = Hash.new 0
    words.each {|word| frequencies[word] += 1}
    words.uniq.each {|word| puts "#{word} #{frequencies[word]}"} 
    #Iterate over the words, and print each one with it's frequency.
    

    【讨论】:

    • 为什么reversesort_by 需要? :-)
    • 非常感谢 Linuxios。这行得通。我得回去看看我做错了什么。我们还没有了解 .uniq 方法,但看起来这就是与众不同的原因,所以我会查一下,以便将来自己使用它
    • @user3324987:当然。原始代码中的问题是您需要在循环中放置,并且不需要所有排序。 uniq 非常简单,它只是返回没有任何重复的数组。所以,["hi", "hi", "the"] 变成了["hi", "the"]
    【解决方案2】:

    我会这样做:

    puts "Type something profound please"
    text = gets.chomp.split
    

    我在这里调用了Enumerable#each_with_object 方法。

    hash = text.each_with_object(Hash.new(0)) do |word,freq_hsh|
      freq_hsh[word] += 1
    end
    

    我在下面调用了Hash#each方法。

    hash.each do |word,freq|
      puts "#{word} has a freuency count #{freq}"
    end
    

    现在运行代码:

    (arup~>Ruby)$ ruby so.rb
    Type something profound please
    foo bar foo biz bar baz
    foo has a freuency count 2
    bar has a freuency count 2
    biz has a freuency count 1
    baz has a freuency count 1
    (arup~>Ruby)$ 
    

    【讨论】:

      【解决方案3】:

      chunk 是一个很好的方法。它返回一个由 2 元素数组组成的数组。第一个是块的返回值,第二个是块返回该值的原始元素数组:

      words = File.open("/usr/share/dict/words", "r:iso-8859-1").readlines
      p words.chunk{|w| w[0].downcase}.map{|c, words| [c, words.size]}
      => [["a", 17096], ["b", 11070], ["c", 19901], ["d", 10896], ["e", 8736], ["f", 6860], ["g", 6861], ["h", 9027], ["i", 8799], ["j", 1642], ["k", 2281], ["l", 6284], ["m", 12616], ["n", 6780], ["o", 7849], ["p", 24461], ["q", 1152], ["r", 9671], ["s", 25162], ["t", 12966], ["u", 16387], ["v", 3440], ["w", 3944], ["x", 385], ["y", 671], ["z", 949]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-02
        • 2013-10-06
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多