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?
Gennady.
···
On Aug 8, 2012, at 3:32 AM, Iwan B. wrote:
I have tho classes A and B1, and b is defined as:
a = A.new
b = a.foo # b is an instance of class B1
I would like to define b directly:
b = B2.new
where the class B2 is defined:
class B2
def initialize
a = A.new
self = a.foo # <<< error!
end
...
end
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
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
def create(...)
A.new(...).foo
end
Kind regards
···
On Wed, Aug 8, 2012 at 12:54 PM, Jan E. <lists@ruby-forum.com> wrote:
This makes no sense. Even if you could redefine "self", it's certainly a
bad idea to change the way objects are created.