Keith Bachand
Keith Bachand

Reputation: 15

RUBY - How to call a method from another class

I'm new to ruby and programming in general and I'm having some issues getting methods to work from another class. The method I'm trying to get to work is new_employee and its option 2 if you run the business.rb business.rb file contains class Business

  class Business
  attr_accessor :name

  def run
    self.welcome
  end 

  def welcome
     while true
       puts "Welcome to Team Green Turf! What do you want to do today?"
       puts "1. Add new customer"
       puts "2. Add new employee"
       puts "3. View current revenue"
       choice = gets.chomp.to_i

      case choice 
         when 1
           puts "hello!"
         when 2
           puts new_employee()
         when 3
           exit

      end 
     end
  end 
end

team_green_turf = Business.new
team_green_turf.run

---------------------------------

employees.rb file

require_relative 'business'

class Employees

  attr_accessor :name

  def initialize(name)
    @name = name
  end 

  def new_employee(name)
    puts "What is the employees name?"
    name = gets.chomp
    e1 = Employees.new(name)
  end 


end 

Upvotes: 0

Views: 3235

Answers (1)

David Grayson
David Grayson

Reputation: 87386

There are two main ideas:

  1. You need to ensure that the Ruby interpreter has loaded the file containing the method before you attempt to call it. In your case, you are executing the code at the botton of business.rb before the employees.rb file has been fully loaded, so the Employee class and its methods will not be defined. You could fix this in many different ways, but I suggest moving the last two lines of business.rb into their own file called run.rb and putting require_relative 'business' at the top of run.rb, and putting require_relative 'employees' at the top of business.rb, and removing the require_relative 'business' from the top of employees.rb. (The Employees class does not actually use or depend on the Business class so it doesn't make sense to require it.)
  2. You need to provide the proper prefixes to the method to get it to be called. In your case, you want to call the function from the Business class, you would write Employees.new_employee. You would also need to change new_employee to be a class method by putting self. before its name when you are defining it: def self.new_employee(name)....

Upvotes: 1

Related Questions