vinod's erudition

we learn everything from failure not from success so keep failing

Home Ruby Rails Javascript Python Agentic AI

Singleton methods simple takes me away

Posted on March 04, 2014 by vinod

Singleton methods

Singleton methods are nothing but adding method to a single object.

class Myclass

    @str = "hello i am mark"
	def @str.check
		self.upcase ==  self
	end

	def self.end
		puts "hello"
	end
	puts Myclass.singleton_methods #->end

	puts @str.singleton_methods #->check

	puts self.singleton_methods #->end

end

cl = Myclass.new
Myclass.end #=> hello

####Explanation:

We are addding methods to single method such as adding check methods to @str object. and adding end method to Myclass class(in Ruby class is an object)

####what self keyword does ?

‘self’ keyword in ruby gives you access to the current object. in class context self refers to current class(which is instance of class Class) inside method self refers to current object of method called.

####ADDING SINGLETON METHOD TO CLASS

class MyClass
	def self.hello
		"hello"
	end
end

####ADDING SINGLETON METHOD TO METHOD

	def mc.hello
		"hello"
	end

####EXAMPLE

class Myclass
	attr_accessor :title

	class << self
		def author
			"paul"
		end
	end 

	def set_author
		"#{@title} by #{self.class.author}"  #while calling a self method you should call using self.class

	end
end

mc =  Myclass.new
mc.title = "Metaprogramming"
puts mc.set_author

####Explanation:

for calling a singleton methods from another method use ‘self.class.methodname’ ####NOTE:

####TO BE SIMPLE :

lets dive in to example

class MyClass
	def size
		24
	end
end

mc,hc=MyClass.new

def hc.size
	50
end

puts mc.size # 23

puts hc.size # 50