Destructive method in ruby

Distructive methods are used to change the object value permanently by itself using bang (!) operator.

‘sort’ returns a new array and leaves the original unchanged.

‘sort!’ returns the same array with the modification.

example
myval = [‘phy’, ‘chem’, ‘bio’]
#myval is of type Array.

myval.reverse returns [“bio”, “chem”, “phy”] but the dont alter the object

p myval

#outputs:
#[‘phy’, ‘chem’, ‘bio’]

But
myval.reverse!
# this method altered the object.

p myval

#outputs:
#[“bio”, “chem”, “phy”]

 The ‘!’ indicates it’s a destructive method. It will overwrite the current array with the new result and returns it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s