From: Quintus Date: 2011-05-26T05:45:43+09:00 Subject: Re: Method that mutates object -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Am 25.05.2011 21:22, schrieb jason solomon: > Say we want to write a String method called clear that takes a given > string and modifies that string to be equal to "". > > Ex. > > str = "string" > > we call str.clear and we get back "", not just "" printed to the screen, > but the value of str is now "" (mutate the original string). > > > I understand that the following code would just print "" to the screen > but not modify the actual str object. > > class String > def clear > "" > end > end > > > How would you write a method that actually modifies the str object? > Just in addition to what the others said, the method String#clear already exists. ================================================= $ ri String#clear = String#clear (from ruby core) - ------------------------------------------------------------------------------ string.clear -> string - ------------------------------------------------------------------------------ Makes string empty. a = "abcde" a.clear #=> "" ================================================= And does exactly what you want it to. Vale, Marvin -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJN3WptAAoJELh1XLHFkqhaG5AH/1mAcLBo9eKzpJg3XHjIXXAr vFOUV9+Ow3hSBZ8Q1KDQrKOVd2QBRkkA2vk7wF7H9KrJCar7wElf0OgJHYmjlEhR HRnnxtoRgdkRo1GoFyvGr7tRzoKlAgPNC93AQFDm7mZFfO6QMtF5aR4xLgWMIZhM vRNMkjs71XE1lmxASvFDVgW4SS1wxJnzDe0LQZncjOOPaZHQQM2P3aR9mHL8Or8O FBvuzqgCptKq5Y69xv/AysLZlRu1ja37J6ggK7LIuLsmT2UaydOc9pVgDaunazrI ym9IASTm/7vmYRKr3FuA98JifEGAEWC6jkuP0MYcLNkGLdhEzkce04FxHdkfodk= =5xGw -----END PGP SIGNATURE-----