From: Josh Cheek Date: 2012-09-07T15:44:04+09:00 Subject: Re: best coding for limiting a value --047d7b5d33e4fd70c604c916eecf Content-Type: text/plain; charset=ISO-8859-1 On Tue, Sep 4, 2012 at 3:13 PM, Regis d'Aubarede wrote: > A) result=value max ? max : value) > > B) > result=value > if value < min then result= min end > if value > max then result= max end > > C) > [min,max,value].sort[1] > > I like (B) best. Initially I liked (C), b/c it's easiest to parse. But I read it as 'select the middle value' Then I figured I should actually read the others, and realized it was "select the closest value in range". But +1 to what Peter Hickman said about picking a good name will make it largely irrelevant which one you choose (i.e. don't just drop this into the middle of some code, wrap it in a descriptive method name). def closest_in_bounds(value) return min if value < min_value return max if max_value < value value end This does make the assumption that your min and max are methods, which assumes you're already following an OO style of writing, but based on your initial examples, it's difficult to tell if this is the case. --047d7b5d33e4fd70c604c916eecf Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable On Tue, Sep 4, 2012 at 3:13 PM, Regis d'Aubarede <= lists@ruby-forum.= com> wrote:
A) =A0result=3Dvalue<min ? min : (value > max ? max : value)

B)
result=3Dvalue
if value < min then result=3D min =A0end
if value > max then result=3D max =A0end

C)
[min,max,value].sort[1]


I like (B) best. Initially I liked (C), b/c it's e= asiest to parse. But I read it as 'select the middle value' Then I = figured I should actually read the others, and realized it was "select= the closest value in range". But +1 to what Peter Hickman said about = picking a good name will make it largely irrelevant which one you choose (i= .e. don't just drop this into the middle of some code, wrap it in a des= criptive method name).

def closest_in_bounds(value)
=A0 return min if value < min_value<= br>=A0 return max if max_value < value
=A0 value
end

This d= oes make the assumption that your min and max are methods, which assumes yo= u're already following an OO style of writing, but based on your initia= l examples, it's difficult to tell if this is the case.
--047d7b5d33e4fd70c604c916eecf--