Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby : How to define a util class?

Tags:

ruby

Can we define utility class with instance methods and then in another class, using object of the utility class, call the instance methods?

For example,

class Usertype # utility class
  def add(a, b)
    c = a + b
    return c
  end
end

class User
  user = Usertype.new

  def test
    return user.add(1,2)
  end
end

Can this be done?

like image 406
Namrata K Avatar asked Dec 28 '22 08:12

Namrata K


2 Answers

I am not sure what you are asking but here is what you can do:

class Usertype
   def add(a,b)
     return a + b
   end
end
class User
  def test
    u = Usertype.new
    return u.add(1,2)
  end
end

Or you can use an instance variable in user:

class User
   def initialize
    @u = Usertype.new
  end
  def test
    return @u.add(1,2)
  end
end
like image 28
Ivaylo Strandjev Avatar answered Jan 20 '23 14:01

Ivaylo Strandjev


Yup, you can achieve that by using modules:

module Usertype
  def self.add(a,b)
    a + b
  end
end
class User
  def test
    Usertype.add 1, 2
  end
end
u = User.new
u.test
like image 155
Martin Samson Avatar answered Jan 20 '23 16:01

Martin Samson