user3477465
user3477465

Reputation: 193

How to create an instance with part of the methods of a class in Ruby?

I have class A with methods X and Y. Now I want to create an instance but only want it to have method X from class A.

How should I do it? Should it be by deleting method Y for the instance when creating it? Your help is appreciated!

Upvotes: 0

Views: 46

Answers (3)

Alex Wayne
Alex Wayne

Reputation: 187312

It's possible to do what you want with ruby, as ruby can be very malleable like that, but there are much better ways. What you want to achieve seems like a really bad idea.

The problem you just described a problem inheritance is designed to solve. So really, you have two classes. Class A and also class B which inherits from class A.

class A
  def foo
    'foo'
  end
end

# B inherits all functionality from A, plus adds it's own
class B < A
  def bar
    'bar'
  end
end

# an instance of A only has the method "foo"
a = A.new
a.foo #=> 'foo'
a.bar #=> NoMethodError undefined method `bar' for #<A:0x007fdf549dee88>

# an instance of B has the methods "foo" and "bar"
b = B.new
b.foo #=> 'foo'
b.bar #=> 'bar'

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118299

Here is one way to solve the problem :

class X
  def a 
    11
  end
  def b
    12
  end
end

ob1 = X.new
ob1.b # => 12
ob1.singleton_class.class_eval { undef b }
ob1.b
# undefined method `b' for #<X:0x9966e60> (NoMethodError)

or, you could write as ( above and below both are same ) :

class << ob1
  undef b
end

ob1.b
# undefined method `b' for #<X:0x93a3b54> (NoMethodError)

Upvotes: 1

coreyward
coreyward

Reputation: 80140

You should not do this. You should instead share the problem you're solving and find a better pattern for solving it.


An example for solving this problem a little differently:

class A
  def x; end
end

module Foo
  def y; end
end

instance_with_y = A.new
instance_with_y.send :include, Foo
instance_with_y.respond_to? :y #=> true

Upvotes: 1

Related Questions