简体   繁体   中英

Iterating over the Hash - Ruby

This is the correct answer below, but I'm not understanding why it is ok to type "puts word" in the last line, whereas it's not acceptable to type "puts x" since it is defined in almost the exact same way

puts "Text please "
text = gets.chomp

words = text.split(" ")
frequencies = Hash.new{0}

words.each { |word| frequencies[word] += 1}

frequencies = frequencies.sort_by { |x, y| y }
frequencies.reverse!
frequencies.each do |word, frequency|
    puts word + " " + frequency.to_s
end

It's defined in the same way, as a code block parameter, but not the same place . Code blocks can use variables provided as parameters or defined inside themselves, so puts word is OK, or in the parent scope (the code which created the block - the "top level" in this case), so puts frequencies would also be ok.

However, x comes from a completely different code block so the block at the bottom doesn't know about it. x only has meaning within the block that you pass to frequencies.sort_by .

It's not defined in the same way.

x is defined in the sort_by block of frequencies.

It's not defined there.

It would work if you had put instead:

frequencies.each do |x, y|
    puts x + " " + y.to_s
end

for example, but x and y aren't defined outside of {}, or in this case, do...end

I think you are confused on the scope of your placeholders. On the last line you use |word,frequency| as your placeholders in frequencies.each do |word, frequency| , whereas your |x,y| is scoped to your first each in frequencies = frequencies.sort_by { |x, y| y } frequencies = frequencies.sort_by { |x, y| y }

As an aside, perhaps it would be best if you renamed your |x, y| to something specific? You can get lost in code if you don't properly define your variables, methods, placeholders etc. Just a thought.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM