Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a #between? for numbers in Crystal?

Tags:

crystal-lang

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.

like image 644
GHajba Avatar asked Aug 03 '18 09:08

GHajba


1 Answers

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.

like image 153
Stephie Avatar answered Sep 24 '22 03:09

Stephie