Sunday, May 26, 2013

What Does the Exclamation Mark "!" do in Ruby?

Okay, had a break through of the meaning of the "!" while testing in the project for Lesson 4.

Original description of the "!" was with other methods like .reverse or .capitalize. It was said that these methods only made a copy of the value and that by adding "!" it would replace it. At first I thought it was just writing extra lines of code that couldn't be seen. What it actually does is replace the variable out permanently whereas without it the output would only be changed in that one instance.

Examples (Orange = input ; White = output):

1. This only changes the output once.

2. Same as above. The original reverse is not in the output because there was no print / puts command.

3. This changes the variable forever! Now "x" is always reversed.

This is what "!" does for methods like .capitalize and .reverse. There might be more to this function in the future.

No comments:

Post a Comment