Like: Ruby range that does not include the first value

With ranges in Ruby, you can do 0..5to include all numbers between 0 and 5. In addition, you can do 0...5to include the same numbers except 5, not included.

(1..5) === 5
=> true
(1...5) === 5
=> false
(1...5) === 4.999999
=> true

Is there a way to exclude the first number instead of the last to get such a result?

(1...5) === 1
=> false
(1...5) === 1.00000001
=> true
+3
source share
4 answers

No, there is no native support for this range. You may need to collapse your own Range-like class if necessary.

+2
source

Besides sending first_arg.succinstead first_arg? No, there is no special support for this.

+1
source

. , . , :

[(1..5).to_s].map{ |s| a,b=s.split('..').map{|i| i.to_i}; (1+a .. b) } #=> [2..5]

Range.new(*[(1..5).to_s].map{ |s| a,b=s.split('..').map{|i| i.to_i}; [1+a,b] }.flatten) #=> 2..5

irb(main):004:0> asdf = (1..5)
=> 1..5
irb(main):005:0> Range.new(asdf.min.succ, asdf.max)
=> 2..5

.

+1

, , , . :

class Range
    def exclusive()
        Range.new(self.first+1, self.last-1)
    end
end

(1..5).exclusive === 5
==>false
(1..5) === 5
==>true

Beware of monkeypatching though, as it modifies the functionality of existing classes. There is probably a better way to do this in this case, but given the question, this is an acceptable answer.

0
source

Source: https://habr.com/ru/post/1781702/


All Articles