Skip to content

Instantly share code, notes, and snippets.

@fronx
Created August 9, 2011 12:55
Show Gist options
  • Select an option

  • Save fronx/1133963 to your computer and use it in GitHub Desktop.

Select an option

Save fronx/1133963 to your computer and use it in GitHub Desktop.
def clip(value, min, max)
value < min ? min :
value > max ? max : value
end
puts clip(34, 10, 32) # => 32
puts clip( 8, 10, 32) # => 10
# or:
def clip(value, range)
case
when value < range.first
range.first
when value > range.last
range.last
else
value
end
end
puts clip(34, 10..32) # => 32
puts clip( 8, 10..32) # => 10
# or: (ha!)
def clip(value, min, max)
{
value < min => min,
value > max => max
}[true] || value
end
puts clip(34, 10, 32) # => 32
puts clip(8, 10, 32) # => 10
# or:
clipped = (min..max).cover?(value) ? value : value > max ? max : min
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment