What is self ?

Self in a Class Method

class Person
def self.species
'Homo sapiens'
end
end

bob = Person.new
bob.species
=> NoMethodError #(undefined method `species' for #<Person:0x0000000001068d48>)

Person.species
=> "Homo sapiens"

Self in an Instance Method

class Person
attr_reader :name

def initialize(name)
@name = name
end

def get_name
name
end
end

bob = Person.new('Bob')
bob.name
=> 'Bob'
bob.get_name
=> 'Bob'
class Person
attr_accessor :name

def initialize(name)
@name = name
end

def change_name(new_name)
self.name = new_name
end
end

bob = Person.new('Bob')
bob.name
=> 'Bob'
bob.change_name('Rick')
=> 'Rick'
bob.name
=> 'Rick'
class Person
attr_accessor :name

def initialize(name)
@name = name
end

def change_name(new_name)
name = new_name
end
end

bob = Person.new('Bob')
bob.name
=> 'Bob'
bob.change_name('Rick')
=> 'Rick'
bob.name
=> 'Bob'

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store