ivan
ivan

Reputation: 6322

Is there a more rubylike way to do output_val = [ input_val, max ].min?

Occasionally I need to do something like this:

output_val = ( input_val < max ) ? input_val : max

and if I'm feeling stingy on space, I might opt for:

output_val = [ input_val, max ].min

Is there a third option that's concise without sacrificing expressiveness?

Upvotes: 0

Views: 55

Answers (1)

Mark Thomas
Mark Thomas

Reputation: 37517

Monkey patch! Doesn't get much more Rubylike than this.

class Numeric
  def unless_over(max)
    [self, max].min
  end
end

Example:

133.unless_over(100) #=> 100
133.unless_over(150) #=> 133

Note: I wouldn't actually do this (I'd use your second example), but I'm guessing this is the spirit of the question.

Upvotes: 2

Related Questions