Why is this variable here?

Why is this variable here?
And should I put ‘word’ there as well ? Rubocop wants me to.

(You can post code directly, in between ``` back ticks - images are harder to read)

See: https://docs.ruby-lang.org/en/2.7.0/Enumerable.html#method-i-sort_by

sort_by returns the value on which to sort the list.

Your frequencies are a hash, and so a collection of key->value pairs, in your case word->count pairs. The sort_by call is returning an array of [word, count] pairs, ordered by count.

2.7.1 :001 > freq = {"a" => 2, "b" => 3, "c" => 1}
2.7.1 :002 > freq.sort_by {|word, count| count}
 => [["c", 1], ["a", 2], ["b", 3]] 
2.7.1 :003 > freq.sort_by {|word, count| word}
 => [["a", 2], ["b", 3], ["c", 1]] 
2.7.1 :004 > 

Notice how line 2 returns the word-count pairs ordered by count, and line 3 returns the word-count pairs ordered by word.

Rubocop may be complaining because you have a named variable, word, which does not get used. You could try replacing ‘word’ with ‘_’.

So, in my code it’s ordered by count ?
‘count’ should be on the same line as the .sortby so its clear what it is doing.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs