x < lower ? lower : x > upper ? upper : x # Or should I just go this way: # class Range; def %(x); x < first ? first : x > last ? last : x ; end ; end # (0..5) % x
Refactorings
No refactoring yet !
dudemeister
October 4, 2007, October 04, 2007 05:49, permalink
not more readable, quite a bit slower, but a bit shorter:
[[lower, x].max, upper].min
Emmett
October 4, 2007, October 04, 2007 10:27, permalink
Adding a method is a good idea. I'd call it "bound" instead though. And nested ternary operators are the devil - how people can remember the precedence (which is different in every language) I have no idea. Clear is better than clever!
class Range
def bound(x)
return first if x < first
return last if x > last
return x
end
end
Mark Wilden
October 4, 2007, October 04, 2007 11:05, permalink
The first version is the most readable. Emmett's is the "spelled-out" version. It is more understandable to a newbie, but less readable to anyone else.
///ark
Given a value and a range, I want to the value, unless it falls outside the range. In that case I want to return the lower or upper bound. Is there a more readable solution which does not involve creating new methods?