1

Given a set of classes defined using Structs, like :

K1=Struct.new(:a,:b)
K2=Struct.new(:c,:d)
...

is it still possible to add a single common method :foo to every class defined that way, or do I need a deep refactoring ?

Factoring such behaviors is normally done using inheritance (or mixins), but I don't know if such a factoring is now still possible, starting with such struct-based class definitions.

1 Answer 1

2

You can simply mix a module into both structures.

module A
  def foo
  end
end

B = Struct.new :a, :b do include A end
C = Struct.new :c, :d do include A end

puts B.new.respond_to? :foo  # => true
puts C.new.respond_to? :foo  # => true

See Module#include and Object#extend for detailed documentation on how this works.

Sign up to request clarification or add additional context in comments.

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.