I still haven’t given up my subscriptions to my ColdFusion based mailing lists. Heck I’ve belonged to them sing 2000. It’s almost like leaving family. Alas I digress, a question came up asking how you would solve this problem in CF.

Say that I have a list of allowed nmbers: 32,48,64,72,144,160,200,288,320,400,512,576,640,720,800

If I give the user the option of selecting a number, and it happens to not be in this list, how might I go about automagically selecting the next lowest number? One exception being if the user selects a number lower than 32, in which case the code should return 32.

Examples: User selects 100, the code would return 72.

User selects 480, the code would return 400.

User selects 25, the code would return 32.

One of the simplest solutions presented was this:

<cfset input = 100 />
<cfset last = listFirst(numbers) />

<cfloop list="#numbers#" index="num">
  <cfif num GT input>
   <cfbreak />
 </cfif>
 <cfset last = num />
</cfloop>

#last#

I thought, how would I do this in ruby. Here’s what I came up with. Definitely more elegant than the above code:

# our test input
input = 25

# change the list to an array
nums = "32,48,64,72,144,160,200,288,320,400,512,576,640,720,800".split(",")

# find all the numbers which would be smaller
target = nums.find_all {|num| input >= num.to_i }

# take the last element of the found elements, or if nil return the first 
# element of the original array
puts target.last || nums.first

Leave a Reply