Skip to content

Instantly share code, notes, and snippets.

@pcreux
Last active May 11, 2020 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcreux/0297feafcdb4f5206c5d to your computer and use it in GitHub Desktop.
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)
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