Issue #11808 has been updated by jeremyevans0 (Jeremy Evans).


`Array#grep` is actually `Enumerable#grep`:

```ruby
Array.instance_method(:grep).owner
=> Enumerable
```

If I had to guess, the cause of the difference is that `Array#each` is implemented in C, and `Test#each` is implemented in Ruby, and this affects Regexp special variable scope.  You see similar behavior as Array in other classes that implement `#each` in C, such as Range or File.

The documentation for the special global variables states: `These global variables are thread-local and method-local variables.`  This indicates to me that the bug is that the variables are accessible inside the `Array#each` block, since that block executes inside the current method, it's not local to the `Array#each` method.  However, I would assume removing the current behavior would break too much existing code.

----------------------------------------
Bug #11808: DIfferent behavior between Enumerable#grep and Array#grep
https://bugs.ruby-lang.org/issues/11808#change-78936

* Author: BenOlive (Ben Olive)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: 2.2.2
* Backport: 2.0.0: UNKNOWN, 2.1: UNKNOWN, 2.2: UNKNOWN
----------------------------------------
Regex special global variables are available within the block for Array#grep, but are nil within the block for Enumerable#grep.

Here is an example that explains it better:

~~~
class Test
  include Enumerable
  def each
    return enum_for(:each) unless block_given?
    yield "Hello"
    yield "World"
  end
end

enum = Test.new
array = ["Hello", "World"]

enum.grep(/^(.)/) {$1} # => [nil, nil]
array.grep(/^(.)/) {$1} # => ["H", "W"]
~~~

Tested on 2.0.0, 2.1.5, & 2.2.2



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>