I’m getting strange behavior when trying to select from a hash created with group_by:
When I run
all_records.group_by(&:opportunity).map{|foo| foo[1].length != 1 }.select{|x| x}
I get some elements back: => [true, true]
Yet when I try and select, with the exact block I mapped:
all_records.group_by(&:opportunity).select{|foo| foo[1].length != 1 }
I get no results: => {}
Just as a sanity check, it works as expected when i first convert the hash to an array with sort:
all_records.group_by(&:opportunity).sort.select{|foo| foo[1].length != 1 }.length
Result: => 2
It’s strange to me, because the first result indicates that the hash recognized the foo[1] command perfectly. What’s causing this?
In the first snippet you are doing a
Enumerable#mapon a hash, with a block that gets a single argument (why don’t you unpack it?), and here you get a pair (as you expected). In the second snippet you are doing aHash#selectagain with a single argument (and again you should unpack the key/value), but here you get only the key, not the pair (because of how the method is implemented, check the source code for details).If you go to the docs for Hash#select, you’ll see it explicitly requires unpacked arguments. Conclusion: always unpack the key/value when iterating hashes with any method: