Last active
May 11, 2020 21:27
-
-
Save pcreux/0297feafcdb4f5206c5d to your computer and use it in GitHub Desktop.
Sizes - Use ruby's comparable to compare clothe's sizes (XS, S, M, L, XL, etc)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Size | |
include Comparable | |
def initialize(str) | |
unless ALL_STRS.include? str | |
raise ArgumentError, "#{str} is not a valid size" | |
end | |
@str = str | |
end | |
attr :str | |
def self.[](str) | |
find(str) | |
end | |
def self.find(str) | |
all.find { |size| size.str == str } or raise ArgumentError, "#{str} is not a valid size" | |
end | |
def self.all | |
Size::ALL | |
end | |
def succ | |
ALL[ALL_STRS.index(str) + 1] | |
end | |
def <=>(other) | |
ALL_STRS.index(self.str) <=> ALL_STRS.index(other.str) | |
end | |
def inspect | |
%|#<Size "#{str}">| | |
end | |
ALL_STRS = %w(XXS XS S M L XL XXL 3XL 4XL 5XL 6XL 7XL) | |
ALL = ALL_STRS.map { |str| Size.new(str) } | |
end | |
p Size::ALL | |
# => [#<Size "XXS">, #<Size "XS">, #<Size "S">, #<Size "M">, #<Size "L">, #<Size "XL">, #<Size "XXL">, #<Size "3XL">, #<Size "4XL">, #<Size "5XL">, #<Size "6XL">, #<Size "7XL">] | |
p (Size['XS']..Size['XXL']).to_a | |
# => [#<Size "XS">, #<Size "S">, #<Size "M">, #<Size "L">, #<Size "XL">, #<Size "XXL">] | |
p Size['XS'] > Size['XL'] | |
# => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment