0

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!

2
  • 4
    That is a strange thing to do. What are you trying to solve? Commented Apr 9, 2014 at 22:39
  • As @RenatoZannon is saying, this is strange. I suspect you should refactor and use a module in stead. module ModuleWithX and module ModuleWithY and then in your new class do include ModuleWithX Commented Apr 9, 2014 at 23:52

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.