module Pigged
  String.class_eval do
    def pig
      newstring = self + self[0]; newstring[0] = ""; newstring += "ay"
      return newstring
    end
  end
end
is the relevant code. What I want to do is make a method, pig!, that modifies the original string. How do I do that, without modifying self, because that is not allowed...?
The keyword self in Ruby enables you to access to the current object — the object that is receiving the current message. The word self can be used in the definition of a class method to tell Ruby that the method is for the self, which is in this case the class.
self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.
One practical use for self is to be able to tell the difference between a method & a local variable. It's not a great idea to name a variable & a method the same. But if you have to work with that situation, then you'll be able to call the method with self.
I've condensed your code a little and added the pig! method :
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
                        You shouldn't modify self.
Use replace or a custom method.
Read 'Writing method "change!" for String' for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With