2015-04-07 60 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