我是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來觀察我的值返回。
我明白這一點,將更好的方法來做到這一點是在循環內建立哈希然後返回整個哈希?使用類似 hash = Hash.new hash.store {input} return hash – SirGed