class RuboCop::Cop::Style::MinMaxComparison
Enforces the use of ‘max` or `min` instead of comparison for greater or less.
NOTE: It can be used if you want to present limit or threshold in Ruby 2.7+. That it is slow though. So autocorrection will apply generic ‘max` or `min`:
- source,ruby
a.clamp(b..) # Same as ‘[a, b].max` a.clamp(..b) # Same as `[a, b].min`
@safety
This cop is unsafe because even if a value has `<` or `>` method, it is not necessarily `Comparable`.
@example
# bad a > b ? a : b a >= b ? a : b # good [a, b].max # bad a < b ? a : b a <= b ? a : b # good [a, b].min
Constants
- COMPARISON_OPERATORS
- GREATER_OPERATORS
- LESS_OPERATORS
- MSG
Public Instance Methods
Source
# File lib/rubocop/cop/style/min_max_comparison.rb, line 54 def on_if(node) lhs, operator, rhs = comparison_condition(node.condition) return unless operator if_branch = node.if_branch else_branch = node.else_branch preferred_method = preferred_method(operator, lhs, rhs, if_branch, else_branch) return unless preferred_method replacement = "[#{lhs.source}, #{rhs.source}].#{preferred_method}" add_offense(node, message: format(MSG, prefer: replacement)) do |corrector| autocorrect(corrector, node, replacement) end end
Private Instance Methods
Source
# File lib/rubocop/cop/style/min_max_comparison.rb, line 80 def autocorrect(corrector, node, replacement) if node.elsif? corrector.remove(range_between(node.parent.loc.else.begin_pos, node.loc.else.begin_pos)) corrector.replace(node.else_branch, replacement) else corrector.replace(node, replacement) end end
Source
# File lib/rubocop/cop/style/min_max_comparison.rb, line 72 def preferred_method(operator, lhs, rhs, if_branch, else_branch) if lhs == if_branch && rhs == else_branch GREATER_OPERATORS.include?(operator) ? 'max' : 'min' elsif lhs == else_branch && rhs == if_branch LESS_OPERATORS.include?(operator) ? 'max' : 'min' end end