我必须向用户询问一个字符串,程序应该对字符串进行排序并将其转换为这样的数组
[["Letter", frequence]]
[["a", 4],["b", 3],["c",3]]
如果是等于频率,则按字母顺序排列。
我有这段代码
puts "Write what you want"
text = gets.chomp
text.downcase!
words = text.split("")
print words
frequencies = Hash.new(0)
words.each do |word|
frequencies[word] += 1
end
frequencies = frequencies.sort_by {|x,y| y}.reverse!
frequencies = frequencies.sort_by {|x| x[1]}
frequencies.each do |word, freq|
puts word + " " + freq.to_s
end
答案 0 :(得分:2)
这应该有效:
str = 'helloworld'
frequency_hash = str.downcase.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }
# => {"h"=>1, "e"=>1, "l"=>3, "o"=>2, "w"=>1, "r"=>1, "d"=>1}
frequency_hash.sort_by { |k,v| [-v, k] }
# => [["l", 3], ["o", 2], ["d", 1], ["e", 1], ["h", 1], ["r", 1], ["w", 1]]
答案 1 :(得分:1)
str = "Baboon"
h = str.downcase.each_char.group_by(&:itself)
h.merge(h) { |_,a| a.size }.sort_by { |c,f| [-f, c] }
#=> [["b", 2], ["o", 2], ["a", 1], ["n", 1]]
我们首先使用String#downcase:
s = str.downcase
#=> "baboon"
然后应用String#each_char:
enum = s.each_char
#=> #<Enumerator: "baboon":each_char>
我们本可以使用String#chars:
s.chars
#=> ["b", "a", "b", "o", "o", "n"]
但是,如果有选择,最好使用枚举器来避免创建临时数组。
通过将枚举器转换为数组,可以看到枚举器的元素:
enum.to_a
#=> ["b", "a", "b", "o", "o", "n"]
但我们不会那样做。接下来,我们在枚举器上调用Enumerable#group_by:
h = enum.group_by(&:itself)
#=> {"b"=>["b", "b"], "a"=>["a"], "o"=>["o", "o"], "n"=>["n"]}
运算符&
首先使用Method#to_proc将方法Object#itself(Ruby 2.2+)转换为proc,然后调用proc。
然后我们使用使用块的Hash#merge形式:
{ |_,a| a.size }
确定合并的两个哈希中存在的每个键的值(这当然是每个键):
g = h.merge(h) { |_,a| a.size }
# => {"b"=>2, "a"=>1, "o"=>2, "n"=>1}
最后,Enumerable#sort_by提供了所需的排序:
g.sort_by { |c,f| [-f, c] }
#=> [["b", 2], ["o", 2], ["a", 1], ["n", 1]]
答案 2 :(得分:0)
mytext = "This is sample text to count all characters in string"
myhash = mytext.downcase.each_char.with_object({}) { |c,h| (h[c] = h.fetch(c,0) + 1) if c =~ /[a-z]/ }
> myhash.sort_by{|k,v| v}.reverse
#=> [["t", 7], ["s", 5], ["i", 4], ["a", 4], ["e", 3], ["n", 3], ["r", 3], ["l", 3], ["c", 3], ["h", 2], ["o", 2], ["m", 1], ["u", 1], ["p", 1], ["x", 1], ["g", 1]]