Hi there
here is my code which is good
puts “Donne moi un texte :”
text = gets.chomp
words = text.split(" ")
frequencies = Hash.new(0)
words.each do |word|
frequencies[word] +=1
end
frequencies = frequencies.sort_by do |word, count|
count
end
frequencies.reverse!
But I wanted to know if i really understand the sort_by method
for example here we are calling the sort_by on frequencies and we attribute word and count to the keys and values right ?
but the second count written is it like telling ruby to sort frequencies according to count ?
please help
Yes, that’s essentially it.
The word
and count
variables are used to represent the key and value in the hash, then we give the criteria of sorting (in this code it’s simply count
).
2 Likes
thank you a lot arkofocolovi 
You’re helpful and I am going to piggy back on this thread instead of starting a new one. Maybe you can explain why this code returns the results the lesson is looking for, but I am being told I didn’t set the hash frequencies correctly.
puts “Give me a quote.”
text = gets.chomp
words = text.split(" ")
frequencies = Hash.new(0)
words.each do |word|
frequencies[word] += 1
end
frequencies = frequencies.sort_by do |word, count|
end
It’s always better to start a new thread for each problem, because we never know how different the problems will be, how long it will take to solve them, and it greatly decreases visibility for those who are reading the forums looking for a problem similar to theirs.
As for your code, your sort_by
doesn’t sort anything, you need to specify which criteria to use for the sorting.
Also, depending on the exercise, they might ask you to sort the hash in decreasing order.
I think they’re also asking you to display the hash right? You’re not doing it in this code.
In this portion of the exercise they aren’t requesting anything be displayed. I am getting the succeeded box and a green check on the upper left by the title of the lesson indicating I’ve completed it.
This is what I am seeing.
And if you get rid of the whole sort_by? Because this exercise doesn’t require any sorting apparently.
1 Like
I removed the entire frequencies = frequencies.sort_by do |word, count| end line and it worked. I got ahead of myself?
Thanks again. Sorry for bothering you.
Great, no problem, good luck for the rest of the course.
1 Like
In a small village library, books are lended for their members for a
week. Details such as name of the book, author, date of purchase,
accession number and avialability status are stored for each book. Given
the details of the ‘n’ books sorted by the accession number of book and
an accession number to search, develop an algorithm and write the
Python code to perform binary search in the given data. Print ‘Found’ or
‘Not Found’ appropriately.
pls send answer for this