Project

General

Profile

Actions

Bug #18793

closed

Select and Find behave differently for hashes

Added by brenogazzola (Breno Gazzola) about 1 month ago. Updated about 1 month ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:108639]

Description

It seems that Hash implements select but not find, which uses the Enumerable version.

irb(main):009:0> { 1..10 => :a, 11 .. 20 => :b }.select { _1 === 12 }
=> {11..20=>:b}

irb(main):010:0> { 1..10 => :a, 11 .. 20 => :b }.find { _1 === 5 }
=> nil

irb(main):011:0> { 1..10 => :a, 11 .. 20 => :b }.select { p _1 }
1..10
11..20

irb(main):012:0> { 1..10 => :a, 11 .. 20 => :b }.find { p _1 }
[1..10, :a]

Expected Behavior:
I expected that both select and find return matches OR that neither select and find return matches

Current Behavior:
Select returns matches but find does not.

Updated by jeremyevans0 (Jeremy Evans) about 1 month ago

I don't think this is a bug. The behavior difference is because Hash#each yields an array of [key, value] and not key and value separately, unlike Hash#select.

You can get the behavior you want by using explicit block variables:

{ 1..10 => :a, 11 .. 20 => :b }.select { |k,| k === 5 }
{ 1..10 => :a, 11 .. 20 => :b }.find { |k,| k === 5 }

Your code could be made to work by adding a definition for Hash#find that yields key and value separately, but I don't think the backwards compatibility issues with such a change are worth it.

Updated by brenogazzola (Breno Gazzola) about 1 month ago

Yeah, I had noticed the difference, but I assumed that "method missing = bug". But you are right. That would be a breaking change for a lot of projects (I hand't thought of that).

Actions #3

Updated by jeremyevans0 (Jeremy Evans) about 1 month ago

  • Status changed from Open to Rejected
Actions

Also available in: Atom PDF