2015-04-07 61 views
0

我是Ruby新手,正在尝试一些简单的练习来弄清楚它是如何工作的。 目前我正在尝试对一个字符串进行排序,找出每个字母在字符串中有多少个字符,然后在散列中返回这些值。一旦我获得了散列中的所有值,我希望能够用其他方法修改该数据。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等。任何帮助,这将是伟大的。我完全使用pp来观察我的值返回。

回答

0

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

+0

我明白这一点,将更好的方法来做到这一点是在循环内建立哈希然后返回整个哈希?使用类似 hash = Hash.new hash.store {input} return hash – SirGed

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