我正在阅读Ruby编程(第4版),我不太明白如何用2个括号迭代for
循环。
require_relative "words_from_string.rb"
require_relative "count_frequency.rb"
raw_text = %{hey hey hey man man bro}
word_list = words_from_string(raw_text)
counts = count_frequency(word_list)
sorted = counts.sort_by {|word, count| count }
top_five = sorted.last(5)
for i in 0...5
word = top_five[i][0] #don't understand why there are 2 brackets.
count = top_five[i][1] #how does the iterator work with 2 brackets.
puts "#{word}: #{count}"
end
words_from_string.rb
def words_from_string(string)
string.downcase.scan(/[\w']+/)
end
count_frequency.rb
def count_frequency(word_list)
counts = Hash.new(0)
for word in word_list
counts[word] += 1
end
counts
end
答案 0 :(得分:2)
如果使用sort_by
进行散列,则会将散列转换为二维数组。
counts = Hash.new(0)
=> {}
counts[1] = 2
=> 2
counts[2] = 1
=> 1
counts
=> {1=>2, 2=>1}
sorted = counts.sort_by{ |k, v| v }
=> [[2, 1], [1, 2]]
sorted[0][1]
=> 1
答案 1 :(得分:2)
top_five
数组由元素组成,这些元素本身就是带有两个元素的数组 - 第一个是单词,第二个是它出现在raw_text
中的次数。
循环迭代这些对并将单词(每个数组的第一个元素,索引0)提取到word
,并将计数(每个数组中的第二个元素,索引1)提取到count
答案 2 :(得分:2)
这是因为'topfive'是一个多维数组(在你的情况下是一个二维),意思是,它是一个包含数组的数组。
如果你打算玩它: 如果你放了topfive [n],它会给你一个结构为[string,int]的数组,在你的例子中是[word,count]。
代码使用两个括号,以便您访问数组中的元素。 在示例中,topfive [i] [0]将获得该单词,topfive [i] [1]将获得计数或单词数
答案 3 :(得分:1)
我玩我的控制台并根据你的答案,我终于明白了!
基本上,first []是主数组的索引,第二个[]是嵌套数组的索引。现在我懂了!辉煌!谢谢你们!
def words_from_string(string)
string.downcase.scan(/[\w']+/)
end
def count_frequency(word_list)
counts = Hash.new(0)
for word in word_list
counts[word] += 1
end
counts
end
raw_text = %{hey hey hey man man bro yo yo yo yo yo ye ye ya oi ui}
word_list = words_from_string(raw_text)
counts = count_frequency(word_list)
sorted = counts.sort_by {|word, count| count}
top_five = sorted.last(5)
print word_list
#produces
["hey", "hey", "hey", "man", "man", "bro", "yo", "yo", "yo", "yo", "yo", "ye", "ye", "ya", "oi", "ui"]
print counts
#produces
{"hey"=>3, "man"=>2, "bro"=>1, "yo"=>5, "ye"=>2, "ya"=>1, "oi"=>1, "ui"=>1}
print sorted
#produces
[["ui", 1], ["ya", 1], ["oi", 1], ["bro", 1], ["man", 2], ["ye", 2], ["hey", 3], ["yo", 5]]
print top_five
#produces
[["bro", 1], ["man", 2], ["ye", 2], ["hey", 3], ["yo", 5]]
for i in 0...5
word = top_five[i][0]
count = top_five[i][1]
puts "#{word}: #{count}"
end
#produces
bro: 1
man: 2
ye: 2
hey: 3
yo: 5
puts top_five[4][1]
#produces
"5"
puts top_five[4][0]
#produces
"yo"