Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify Self, Ruby

Tags:

ruby

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...?

like image 559
Bobby Tables Avatar asked Apr 30 '12 20:04

Bobby Tables


People also ask

What does self do in Ruby?

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.

What does self mean when used in a class Ruby?

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.

What is the use of self in rails?

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.


2 Answers

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
like image 111
Kassym Dorsel Avatar answered Oct 06 '22 23:10

Kassym Dorsel


You shouldn't modify self.

Use replace or a custom method.

Read 'Writing method "change!" for String' for more information.

like image 29
Sully Avatar answered Oct 06 '22 22:10

Sully