Pages

Thursday 3 January 2013

Fascinating Ruby - Part 1

Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. It was also influenced by Eiffel and Lisp. Ruby supports multiple programming paradigms, including functional, object oriented, imperative and reflective. It also has a dynamic type system and automatic memory management; it is therefore similar in varying respects to Smalltalk, Python, Perl, Lisp, Dylan, Pike, and CLU.

The above is a small technical introduction to ruby.  When I started working with ruby I understands ruby is very powerful, efficient and with easy syntax that very helpful for coding. Ruby have a very large set of powerful array and string functions. By using these functions we can get the job done very easily by writing single line of code. For same purpose we need to write number of lines of code in may other languages. Here am going to introduce some such function that come across my work and very useful.

map/collect

There is no functional difference between map and collect as per my knowledge. This is very useful and powerful ruby array function. Using this function we can manipulate array by writing a single line of code. Let see an example.
>> a = [2,6,4,9,3]
>> a.map {|x| x+1}
=> [3,7,5,10,4]
If we use collect also same result will get.
>> a=[2,6,4,9,3]
>> a.collect {|x| x+1}
=> [3,7,5,10,4]
Here we are adding 1 to each element of an array. And doing it in single line."map and collect" is useful when we need to manipulate every element of an array.

select

If we need to implement some conditions on elements of an array and return the values here comes select.Let see an example.
>> a = [2,5,8,4,9,3,6,7]
>> a.select {|x| x if x%2==0}
=> [2, 8, 4, 6]
Here the array contains both even and odd number. We need to get only the even numbers. The select function doing it easily in single line. Let look in to a string example. Consider an array of strings with different lengths. We need to get the words with length greater than 5. Using select we can do it easily.
>> a = ["Hai","Tendulker","Hello","Fantastic"]
>> a.select {|x| x if x.length > 5 }
=> ["Tendulker", "Fantastic"]


                                                  Here one thing you should notice, these functions returning the result. The parent array or list is not changed. After the process if you print the array it will give the old array as unchanged. So while using these functions you need an assignment.
 
>> a = ["Hai","Tendulker","Hello","Fantastic"]
>> b = a.select {|x| x if x.length > 5 }
=> ["Tendulker", "Fantastic"]
>> a
=> ["Hai","Tendulker","Hello","Fantastic"]
>> b
=> ["Tendulker", "Fentastic"]
We will discuss about more such cute functions in the coming posts.                                                                                                                              To be continued

No comments:

Post a Comment