Search

Thursday, December 13, 2007

Support for range in programming languages

DSCF2530

The .NET platform and the languages on top of it have limited or no support for range of values. Data ranges are one of the most common data-types and somehow it's not there. Funnily most programmers do not even seem to miss it (unless of course if you have used Ruby).

How would you specify a valid range of age and validate user data against it? If you know the maximum and minimum values, at max you'd define a MaxAge and MinAge consts and strew the code with if(age < MinAge|| age >MaxAge). Or maybe you'll define a class to encapsulate this and add a IsValid method.

However, in Ruby, Range is a standard DataType like say string. To do the above processing you'd do

age = 1..120

print age.include?(50)
print age.include?(130)


print age === (50) # more easier way to do include? test using the === operator


So intuitively you create a range using start..stop.


Creating a range of data is also very simple. Say you want to generate the column numbers for an excel sheet, you'd do the following

column = 'A'..'ZZ'

column.to_a # creates an array of all the values

column.each {|v| puts "#{v}\n"}

Similarly ranges can be easily created for any class by implementing some special methods. On ruby the support of Range is in the compiler and makes the code very easy to develop and intuitive.


>>Cross posted here

No comments: