Ruby构建和返回哈希

时间:2015-04-07 04:06:03

标签: ruby hash

我是Ruby的新手,我正在尝试一些简单的练习来弄清楚它是如何工作的。 目前我正在尝试对字符串进行排序,找出字符串中每个字母的数量,然后在散列中返回这些值。一旦我获得了散列中的所有值,我希望能够使用其他方法修改该数据。

    require 'pp'

    def countLetters
      #creating variables for processing
      start = "If debugging is the process of removing software bugs, then programming must be the process of putting them in."
      alph = "abcdefghijklmnopqrstuvwxyz"
      output = alph.each_char do |i|
        char = alph[i]

        # moving all letters to lower case
        num = start.downcase.count i
        # pass the char and value into a hash
          if num >= 1
          #puts "#{char} = #{num}"
          return [{:letter => char, :value => num}]
        end
      end
    end

    pp countLetters

我可以让它返回第一个值,但我似乎无法弄清楚如何迭代方法返回值2,3,4等,直到我收到nil。对此的任何帮助都会很棒。我在这里只使用pp来观察我的价值观。

2 个答案:

答案 0 :(得分:0)

用p替换第15行中的return似乎打印了其余的值。 return导致它退出each_char循环

答案 1 :(得分:0)

我想出来了。我错误地构建了哈希。以下是我解决这个问题的方法。

    require 'pp'

    def countLetters
      #creating variables for processing
      start = "If debugging is the process of removing software bugs, then programming must be the process of putting them in."
      alph = "abcdefghijklmnopqrstuvwxyz"
      output = Hash.new
      alph.each_char do |i|
        char = alph[i]
        # moving all letters to lower case
        num = start.downcase.count i
        # pass the char and value into a hash
        if num >= 1
          #puts "#{char} = #{num}"
          output.store (char) , (num)
        end
      end
      return output
    end

    pp countLetters