ruby - How do i require and include a module in the initialize method -
im trying dynamically require , include modules inside initialize method.
# file: object.rb class object attr_accessor :array def initialize array @array = array @array.each |f| require_relative "#{f}" include f.capitalize # method name same filename puts @variable # property included method end end end object = object.new ['a','b','c'] with these module files
# file: a.rb module @variable = 'string a' end and on b , c
i keep getting error :
`block in initialize': undefined method `include' what doing wrong here , there better way achieve i'm trying do?
the reason can't call include in initialize include method that's defined on classes , modules, inside of instance method initialize implicit receiver object of class, not class itself.
since need methods available on newly created object, can use extend instead of include. extend per-object version of include in adds methods of given module singleton methods object rather adding them instance methods module or class.
Comments
Post a Comment