ruby / ruby/rbs

The `range[T]` type definition is to restrictive

Open
#1,493 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
2.2k
Forks
256
Avg merge
6d 17h
Merged PRs (30d)
37

Description

The current definition, type range[T] = Range[T] | _Range[T] is mostly correct, except it implicitly requires T to implement <=>: Range cannot be constructed unless T defines <=>. This imposes the <=> limitation on _Range[T], which doesn't actually require it:

MyInt = Struct.new(:to_int)
MyCmpInt = Struct.new(:to_int) do
	def <=>(rhs) = to_int <=> rhs.to_int
end

MyRange = Struct.new(:begin, :end, :exclude_end) do
	alias exclude_end? exclude_end
end

rng1 = MyInt.new(1)..MyInt.new(2)       #=> bad value for range (ArgumentError)
rng2 = MyCmpInt.new(1)..MyCmpInt.new(2) #=> ok!

myrng1 = MyRange.new(MyInt.new(1), MyInt.new(2))       #=> ok!
myrng2 = MyRange.new(MyCmpInt.new(1), MyCmpInt.new(2)) #=> ok!

This is particularly relevant for functions which accept range[int] (or range[int?]), such as String#[]:

puts "hello world"[rng2]   #=> el
puts "hello world"[myrng1] #=> el
puts "hello world"[myrng2] #=> el

The current definition would preclude myrng1 from being a valid argument, as MyInt doesn't define <=>. The solution, I think, is to change range[T]'s definition:

type range[T] = Range[T & Comparable::_WithSpaceshipOperator] | _Range[T]

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the range[T] type definition and the String#[] signature discussed in the issue. Check the existing Range[T] and _Range[T] constraints, then verify the shown MyInt/MyRange cases and String#[] calls accept the intended range types.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
tooling
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.