In Ruby, an instance method is a method declared in a class, that's:
- Created by adding method name after
def
in a class; - Callable only on class instance;
- Allowed to declare new instance variables inside;
- Able to access/modify class instance variables and class variables;
- Able to call class methods.
Created by Adding Method Name After def
in a Class
An instance method can be created by simply adding the name of the method after the def
keyword, for example, like so:
class Foo def bar "bar" end end
Callable Only on Class Instance
A class instance method can only be called on an instantiated object:
class Foo def bar "bar" end end foo = Foo.new puts foo.bar #=> "bar"
If you try to call it on the class itself, it will raise an error:
# undefined method `bar` for Foo:Class (NoMethodError)
puts Foo.bar
Allowed to Declare New Instance Variables Inside
Ruby allows declaration of new instance variables inside an instance method:
class Foo def baz @name = "foo" end def bar "#{@name}bar" end end foo = Foo.new foo.baz puts foo.bar #=> "foobar"
Although, this is allowed, you should generally avoid it and initialize instance variables in the constructor method instead.
Able to Access/Modify Class Instance Variables and Class Variables
The following code shows how you can access instance variables and class variables in an instance method:
class Foo @@separator = "," def initialize() @name = "foo" end def bar "#{@name}#{@@separator}bar" end end foo = Foo.new puts foo.bar #=> "foo,bar"
Similarly, an instance method may modify values of instance variables and class variables:
class Foo @@separator = "," def initialize() @name = "foo" end def separator=(val) @@separator = val end def self.separator @@separator end def bar "#{@name}#{@@separator}bar" end end foo = Foo.new foo.separator = "|" puts foo.bar #=> "foo|bar" puts Foo.separator #=> "|"
Able to Call Class Methods
You may call a class method from an instance method, for example, like so:
class Foo def self.capitalize(arr) arr.map { |item| item.capitalize } end def bar Foo.capitalize(['foo', 'bar']) end end foo = Foo.new puts foo.bar #=> "Foo" "Bar"
You may also call the class method as a symbol:
class Foo def baz "baz" end def bar :baz end end foo = Foo.new puts foo.bar #=> "baz"
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.