Shane
Shane

Reputation: 5667

variable having access to instance method

class BankAccount

  def self.create_for(first_name, last_name)
    @accounts ||= []
    @accounts << BankAccount.new(first_name, last_name)
  end

  def initialize(first_name, last_name)
    @balance = 0
    @first_name = first_name
    @last_name = last_name
  end

 def self.find_for(first_name, last_name)
    @accounts.find{|account| account.full_name == "#{first_name} #{last_name}"}
  end

  def full_name
    "#{@first_name} #{@last_name}"
  end

end

How does the method self.find_for works?. I am getting confused on how the account variable has access to full_name method?.

bankacc = BankAccount.create_for "Kevin", "Shane"
BankAccount.find_for("Kevin", "Shane")
puts bankacc.inspect

Upvotes: 0

Views: 48

Answers (2)

mzoo
mzoo

Reputation: 36

Maybe it helps you to understand the concept if you split the file into two.

This class creates and keeps track of BankAccount instances:

class BankAccounts
 def self.create_for(first_name, last_name)
   @accounts ||= []
   @accounts << BankAccount.new(first_name, last_name)
 end

 def self.find_for(first_name, last_name)
   @accounts.find{|account| account.full_name == "#{first_name} #{last_name}"}
 end
end

This is just a dumb class which you can create instances of:

class BankAccount
  def initialize(first_name, last_name)
    @balance = 0
    @first_name = first_name
    @last_name = last_name
  end

  def full_name
    "#{@first_name} #{@last_name}"
  end
end

In self.create_for you are creating a new account and putting it into the variable @accounts which is "global" (a class variable) inside BankAccounts. Your new instance of a bank account is stored in @accounts so when you use self.find_for, it can look in @accounts to find it there.

@accounts.find{|account| account.full_name == "#{first_name} #{last_name}"} essentially means:

"Look into the @accounts Array, and for every account instance (that is, an instance of BankAccount) see if the full name matches. full_name is a method I may use to inspect a BankAccount instance."

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118261

Because you code it like that.

Look the line @accounts << BankAccount.new(first_name, last_name).

It means @accounts holds all BankAccount objects. Now full_name is an instance method of the instances of the class BankAccount.

Now in the below line -

 @accounts.find { |account| account.full_name == "#{first_name} #{last_name}"}

#find method passing each such BankAccount object(account) to the block, and account is calling the method full_name, being an instance of the class BankAccount.

Nothing wrong here.

Upvotes: 1

Related Questions