Keith Schacht’s Weblog

Subscribe

💡 TIL: Ruby’s clamp method reduces conditionals

24th February 2025

You can constrain a variable to be within a range using clamp:

5.clamp(1, 10)  # => 5
-3.clamp(1, 10) # => 1
15.clamp(1, 10) # => 10

More recent articles

This is Ruby’s clamp method reduces conditionals by Keith Schacht, posted on 24th February 2025.

Part of series Today I Learned

  1. pick is the single-value version of pluck in Rails - Nov. 26, 2024, 11:24 p.m.
  2. Elegant solution to versioning an API - Feb. 24, 2025, 3:13 p.m.
  3. Regex within string square brackets - Feb. 24, 2025, 3:16 p.m.
  4. Ruby's clamp method reduces conditionals - Feb. 24, 2025, 3:19 p.m.

Previous: Regex within string square brackets