From: Robert Klemme Date: 2010-09-13T23:21:46+09:00 Subject: Re: Converting from one class to another in Ruby On Sun, Sep 12, 2010 at 3:34 AM, Harry Spier wrote: > Dear list members, > > I have an application with a class Binary_matrix < Array (which is just The first thing I'd do differently is to cut off this inheritance. Inheriting from core classes is rarely a good idea. In this case you *use* an array for your storage of a binary matrix which is an implementation detail that should be hidden inside the class. Also I am sure you do not want all public Array methods to be available for users of Binary_matrix. So delegation is a much better option here. > a two dimensional array filled with zeroes and ones).  I also have other > classes which have to_Binary_matrix methods to convert objects of their > class to Binary_matrix objects. > > The Ruby code I came up with to do the conversions is as follows. > > class A >  def to_Binary_matrix(from_initialize_method = false) >     ...some logic to convert class A object to binary_matrix_format >     if from_initialize_method >        return an_A_type_object_in_binary_matrix_format >    else >        return > Binary_matrix.new(an_A_type_object_in_binary_matrix_format) >    end >  end > end I find it hard to come up with good suggestions since a lot is missing in this example (for example how you call it from #initialize). Why don't you have a method some_logic_to_convert_class_A_object_to binary_matrix_format which is then called from #initialize and from to_Binary_matrix? That seems the most natural solution and then you do not need the flag in the first place. > class B >  def to_Binary_matrix(from_initialize_method = false) >     ...some logic to convert class B object to binary_matrix_format >     if from_initialize_method >        return a_B_type_object_in_binary_matrix_format >    else >        return > Binary_matrix.new(a_B_type_object_in_binary_matrix_format) >    end >  end > end > > class Binary_matrix < Array >   def initialize arg >      self.replace arg.to_Binary_matrix(true) >   end > end > > This allows me to do: > > a = A.new > an_A_as_a_Binary_matrix_object = a.to_Binary_matrix > b_as_a_Binary_matrix_object = Binary_matrix.new(b) > > It works but it seems a little clunky to me.  Is their a more Rubyish or > elegent way of doing this.  In particular is it possible to get rid of > the flag I use (from_initialize_method) to keep me from getting into an > infinite loop as I go between the .to_Binary_matrix methods and the > initialize method in Binary_matrix It looks absolutely clunky. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/