Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an exclusive range to inclusive range in Ruby?

I have an exclusive range of integers, e.g.

range = 1000...10001

I would rather work with inclusive ranges all the way, but the reason I have this is because when I tell ActiveRecord to store an inclusive range in PostgreSQL, I get the exclusive version when I query it back.

I want to convert it into an inclusive range, e.g. 1000..10000.

I'm doing:

(range.begin)..(range.end-1)

However it feels clunky and un-ruby-ish.

My whole API relies on passing ranges, but I'm also considering storying 2 values or storing an array in Postgres instead of a range.

Is there a better way to do this?


Edit (some clarifications)

I want to do this as efficiently as possible, given the large difference between the ranges

My use case is to use the begin and end part of the ranges. I'm not actually iterating over them or checking inclusion. I just thought that a ruby range is a nice way to represent the actual range for e.g. displaying a price ($ 1.000 - $ 10.000)

like image 486
Cristian Avatar asked Oct 21 '25 01:10

Cristian


1 Answers

I would use Range#min and Range#max:

exclusive_range = (1000...10001)
inclusive_range = (exclusive_range.min..exclusive_range.max)
#=> 1000..10000
like image 144
spickermann Avatar answered Oct 23 '25 14:10

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!