Pages

Friday 4 January 2013

Destructive Functions in Ruby - Part 1


As I said in the previous post those functions does not change the parent array. But adding a very slight difference we can get the job done. We can do this by using "Destructive" function. Don't be afraid by seeing the name. This functions are the function with same name. The only difference is there will be an exclamatory symbol at the end of function name. Let see an example. Lets take the same above example.

select!

 
>> a = ["Hai","Tendulker","Hello","Fantastic"]
>> a.select! {|x| x if x.length > 5 }
=> ["Tendulker", "Fantastic"]
>> a
=> ["Tendulker", "Fentastic"]
In the above example the parent array has been changed after the function execution. So thats why these functions are called "Destructive" functions

map!/collect!

These functions are also "destructive" functions and change the parent array.Lets see the examples.
>> a = [2,6,4,9,3]
>> a.map! {|x| x+1}
=> [3,7,5,10,4]
>> a
>> => [3,7,5,10,4]
>> a = [2,6,4,9,3]
>> a.collect! {|x| x+1}
=> [3,7,5,10,4]
>> a
>> => [3,7,5,10,4]
I think that the above examples will give a basic introduction to "Destructive" functions in ruby. Will discuss about more such type of function in the coming posts.
                                                                                                     To be continued

No comments:

Post a Comment