I was wondering if I simply cannot find a between
method for numbers in Crystal.
In Ruby, there's the Comparable#between?
method which can (among others) compare two numeric values (my specific case).
Background: I want to achieve a not-between solution without using
variable < 2 || variable > 5
I tried 5.between(2,5)
and 5.between?(2,5)
but all I got was a compilation error:
Error in line 1: undefined method 'between?' for Int32
I ended up with extending the number structure:
struct Number
def between?(a, b)
self <=> a >= 0 && self <=> b <= 0
end
end
Question 2: Is my solution above a feasible one? If not, suggestions are welcomed.
In crystal you can write 2 <= variable <= 5
, which is easier to read and gives you greater control over inclusivity/exclusivity at each end of the range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With