This makes no sense. Even if you could redefine “self”, it’s certainly a
bad idea to change the way objects are created. Why would you want an
object “mascerading” as a completely different object?
So you’ll have to stick with the class method (though I have no idea
what this is for).
def initialize
a = A.new
self = a.foo # <<< error!
end
…
end
But i cannot define self in the constructor…
You cannot re-define self, it is defined for you to be the current
instance of class B2. Why do you need it? Even if it were possible,
don’t you find it weird - you create and instance of B2 with B2.new, but
get back the instance of B1?
This is the ‘real’ case (used for .xlsx files generation, via axlsx
gem):
p = Axlsx::Package.new
wb = p.workbook
wb.styles.add_style sz: 16, b: true, alignment: { horizontal: :center }
wb.add_worksheet(:name => “Basic Worksheet”) do |sheet|
…
I don’t need the package object ‘p’, except for get a workbook. But i
want to create a custom worksheet class, so i can define my predefined
styles:
Inside initialise method: @my_styles = {} @my_styles[:heading] = styles.add_style sz: 16, b: true, alignment: {
horizontal: :center }
def apply_style(name) @my_styles[name.to_sym]
end
Remark that ‘styles’ is a workbook method.
Finally:
wb = MyWorkbook.new
…
sheet[“B1”].style = wb.apply_style :boo
This makes no sense. Even if you could redefine “self”, it’s certainly a
bad idea to change the way objects are created.
And especially instance “a” would be lost unless instances of class B1
have a reference back to an instance of A. Basically instance of A in
this scenario is completely superfluous. If B1’s can only be created
via A.new then a method like this would be the way to go