5

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.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
GHajba
  • 3,665
  • 5
  • 25
  • 35

2 Answers2

11

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.

Stephie
  • 3,135
  • 17
  • 22
  • Thanks. I updated the question with my intent: I want the between to use it as a not-between check later. – GHajba Aug 03 '18 at 13:41
  • 1
    `!(2 <= variable <= 5)`. Or just `variable < 2 || variable > 5`. Your second solution is not really needed, just do two comparisons, it's much more clear than `between`, which hides the information about inclusive/exclusive comparision. – asterite Aug 03 '18 at 14:03
  • 1
    Another option is [`Range#includes?`](https://crystal-lang.org/api/latest/Range.html#includes?(value)-instance-method): `(2..5).includes?(variable).`But still, I think comparison operators reads much better – Johannes Müller Aug 04 '18 at 11:49
0

From a deleted answer but I still like it:

You can use a similar method Range#includes? (or #covers).

rogerdpack
  • 62,887
  • 36
  • 269
  • 388