Instance and Class methods

Think about this from our previous BankTransaction class, bank_transaction.rb file. It makes no sense having transaction without a bank name or location right?, what if we changed our class name to bank instead and add some methods names and location.You will realize that our banks do not share names but share other methods(prevously mentioned). This means each instant of the our bank will have a different names and locations but transactions will remain the same.Therefore we can call name and location on the instances bank(instance methods) and call the above methods on class bank itself

image

Class Method

General syntax for class method is like so:

Way 1

1
2
3
4
5
class  Bank
  def self.just_arrived
   "pick your ticket from the machine" 
  end
end

Way 2

1
2
3
4
5
6
7
class  Bank
  class << self
      def just_arrived
       "pick your ticket from the machine" 
      end
  end
end

Way 3

1
2
3
4
5
class  Bank
  def  Bank.just_arrived
    "pick you ticket from the machine"
  end
end

All the above are valid syntax for class method. class method on class and are called on the class itself and not its instance.

Therefore pick from last syntax way 3 that is

1
2
3
4
5
6
7
8
$irb
> class  Bank
>   def  Bank.just_arrived
>     "pick you ticket from the machine"
>   end
> end
> Bank.just_arrived
=>"pick you ticket from the machine"

Instance Method

These are method call on instance of class, along along we have calling instance method.Remeber when we called to_s on 2 , i.e 2.to_s.to_s is an instance method being called on an instance of Integer class

Exercise

write the class Bank with the following methods:

  1. have_picked_up_ticket (class method)

  2. have_valid_id? taking response as arguement (class method)

use above code as reference

  1. bank_name taking name as parameter(instance method)

  2. location taking locaation as parameter(instance method)