7c45f63f61e478233f0c2ad3006b178c

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?

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 !

D41d8cd98f00b204e9800998ecf8427e

dudemeister

October 4, 2007, October 04, 2007 05:49, permalink

2 ratings. Login to rate!

not more readable, quite a bit slower, but a bit shorter:

[[lower, x].max, upper].min
22100344f91ad34ad9fb8fb6b6940a84

Vamsee

October 4, 2007, October 04, 2007 06:39, permalink

2 ratings. Login to rate!
[lower, x, upper].sort[1]
D41d8cd98f00b204e9800998ecf8427e

Emmett

October 4, 2007, October 04, 2007 10:27, permalink

1 rating. Login to rate!

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
48641c4be1fbe167929fb16c9fd94990

Mark Wilden

October 4, 2007, October 04, 2007 11:05, permalink

No rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel