Home > database >  Accessing Class method from another file in Ruby
Accessing Class method from another file in Ruby

Time:01-26

Just for learning , how we can access a class method from another file in ruby. for example

file1.rb

class Test1

  def abc
    #  ...
  end

  def xyz
    # ...
  end
end 

for example if i have to access method abc from class Test1 in file1.rb in another file lets say in file2.rb,

file2.rb

require "file1.rb"

class Test2

# here I would like to call method abc in class Test1
end

CodePudding user response:

Instantiate the class and then call the method. You can do this in two lines or one.

# file1.rb
class Test1
  def abc
    ...
  end
end

# file2.rb
require "file1"

class Test2
  def a_method
    # altogether
    Test1.new.abc

    # to store an object of Test1
    test1 = Test1.new
    test1.abc
  end
end
  •  Tags:  
  • ruby
  • Related