I know my question is pretty simple, but I can't manage to find an answer on the internet.
I have a hash called sorted_frequency. I want to output it as a table using the gem hirb. At the time I just have been able to print the hash under the default field names (0, 1). So it looks like that:
0 1
wordA ntimes
wordB mtimes
wordC rtimes
I'd like to rename the field names so it would be something like this:
words number of times
wordA ntimes
wordB mtimes
wordC rtimes
My actual code is this:
#needs to install 'docx' and 'hirb' gems
require 'docx'
require 'hirb'
doc = Docx::Document.open('monografia.docx')
text_listed = doc.to_s.downcase.split(" ")
forbidden_list = ["o", "si", "em", "ha", "no", "és", "amb", "i", "/","el",
"la", "els","les", "l'", "lo", "los", "en", "n'", "na", "es", "ets", "s'",
"sa", "so", "ses", "sos", "un", "una", "unes", "uns", "a", "que", "s'",
"al", "de","del", "per", "ens", "als", "com"]
clean_text= text_listed - forbidden_list
frequency = Hash.new 0
clean_text.each { |word| frequency[word] += 1 }
sorted_frequency = Hash[frequency.sort_by{ | word, times | -times }[0..20]]
puts Hirb::Helpers::AutoTable.render(sorted_frequency)
Again, I'm sorry if this a newbie question
EDIT:
As all my code has been asked, I'll explain it. It opens a docx document with the help of a gem called 'docx'. After that, it splits the doc by spaces and creates an array. After that, I remove some words I don't want to count (those included in the forbidden_list). Then I create a hash where the key is the word, and the value is the number of times that word appears in the docx. After that, I sort that hash and output using the gem 'hirb. The problem is I just don't know how to name the fields of the table created. I hope someone can help me.
According to the hirb docs,
AutoTable.render()
takes an argument which can be an array_of_arrays or an array_of_hashes. But because your hash argument worked, I looked at your table output, and I decided to try to merely add an option to change the column names that you got:It worked. What must be happening is:
AutoTable.render()
expects an array--either an array_of_arrays or an array_of_hashes--and if the method doesn't get an array as an argument, it callsto_a()
on the argument. Take a look at what happens to your hash:There's the array_of_arrays that
AutoTable.render()
needs. Rearranging a little, the array_of_arrays looks like this:For an array_of_arrays, the column headers in the table are the index positions in each row array. The options for
AutoTable.render()
let you specify which columns/index positions to include in the table and their order, and the options allow you to convert the column headers to something more desirable.Here's a more general example:
====
====
===
=====