Change "I", "Ruby"

module Pigged String.class_eval do def pig newstring = self + self[0]; newstring[0] = ""; newstring += "ay" return newstring end end end 

- the corresponding code. I want to make the pig! method pig! which modifies the original string. How to do this without changing yourself, because it is not allowed ...?

+6
source share
4 answers

You must not change yourself.

Use replace or a custom method.

Read the ' Change! "Recording Method for String 'for more information.

+3
source

I shortened your code a bit and added the pig! method pig! :

 module Pigged String.class_eval do def pig self[1..-1] + self[0] + 'ay' end def pig! self.replace(pig) #self.replace(self[1..-1] + self[0] + 'ay') end end end 
+13
source

For String, you can use self.replace to change the content.

For other classes, I do not think that he can change himself if he does not create a new object.

+4
source

There is nothing wrong with modifying self , you cannot assign it to it, but you can use access methods to change it or change instance variables if you have direct access to them. String#replace is an accessory in this particular case.

Another example:

 class Array def delete_first_element! self[0..0] = [] end end a = [1,2,3] b = a a.delete_first_element! puts a.inspect # [2,3] puts b.inspect # [2,3]! 

One thing to remember is that you change all the links of the same object ( b in my example)!

+1
source

Source: https://habr.com/ru/post/914576/


All Articles