Skip to content

Instantly share code, notes, and snippets.

@mikesimons
Created September 17, 2010 12:48
Show Gist options
  • Save mikesimons/584176 to your computer and use it in GitHub Desktop.
Save mikesimons/584176 to your computer and use it in GitHub Desktop.
class Range
def min
first > last ? last : first
end
def max
last > first ? last : first
end
def clamp(v)
(v < min ? min : (v > max ? max : v))
end
end
@hosiawak
Copy link

if you feel dirty for patching core classes:

module Clamp
  def min
    first > last ? last : first
  end

  def max
    last > first ? last : first
  end

  def clamp(v)
    (v < min ? min : (v > max ? max : v))
  end
end

puts (0..360).extend(Clamp).clamp(370)
puts (360..0).extend(Clamp).clamp(370)
puts (360..0).extend(Clamp).clamp(-10)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment