Issue #15813 has been reported by osyo (manga osyo).

----------------------------------------
Feature #15813: Proposal: Add exception support in `Range#first`
https://bugs.ruby-lang.org/issues/15813

* Author: osyo (manga osyo)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------

## Current status

Calling `Range#last` in endless range(`(1..)`) raises an exception.


```ruby
# OK
p (1..Float::INFINITY).end   # => Infinity
p (1..).end                  # => nil
p (1..Float::INFINITY).last  # => Infinity

# NG: Raise error: in `last': cannot get the last element of endless range (RangeError)
p (1..).last
p (1..).last(1)
```

But, calling `Range#first` in beginless range(`(..1)`) does not raise an exception.

```ruby
# OK
p (-Float::INFINITY..1).begin  # => -Infinity
p (..1).begin                  # => nil
p (-Float::INFINITY..1).first  # => -Infinity

# OK: Does not raise
p (..1).first   # => nil

# NG: Raise error: in `each': can't iterate from NilClass (TypeError)
p (..1).first(1)
```

I think the current situation is not consistent, so it is necessary to move the behavior to one side or the other.
Also, in the case of `Range#last`, an exception is explicitly raised.
see: https://github.com/ruby/ruby/blob/6a3165e19dfa21babfb2ef1f1c20c9930410b0ec/range.c#L1100-L1102


## Proposal

Added support to raise an exception for `Range#first` too.

### Before

```ruby
# OK
p (-Float::INFINITY..10).begin  # => -Infinity
p (..10).begin                  # => nil
p (-Float::INFINITY..10).first  # => -Infinity
p (..10).first                  # => nil
p Range.new(nil, 10).first      # => nil

# NG: Raise error: in `each': can't iterate from NilClass (TypeError)
p (..10).first(1)
```


### After

```ruby
# OK
p (-Float::INFINITY..10).begin  # => -Infinity
p (..10).begin                  # => nil
p (-Float::INFINITY..10).first  # => -Infinity

# NG: Raise error: in `first': cannot get the first element of beginless range (RangeError)
p (..10).first
p Range.new(nil, 10).first
p (..10).first(1)

# in Ruby 2.6.1
p Range.new(nil, 10).first
# Error: in `initialize': bad value for range (ArgumentError)
```

Thank you.

pull request : https://github.com/ruby/ruby/pull/2163



-- 
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>