From: Harry Spier Date: 2010-09-14T11:35:09+09:00 Subject: Re: Converting from one class to another in Ruby Dear Robert, Many thanks for your reply. I have simplified somewhat. Its an OCR application where Binary_matrix is a black and white pixel representation of a page of text(or line of text, or letter or part of a letter etc.). There are many different objects which are to be converted into Binary_matrix such as the above portions of an existing Binary_matrix object, or Rmagick ImageList objects, or graphic objects processed by other packages than RMagick. This list will definitely grow in the future so for that reason I wanted the conversion to Binary_matrix logic to reside in the class being converted to Binary_matrix not in the Binary_matrix class. I.e. I didn't want a list of statements in Binary_matrix initialize method like: if arg.class == ImageList then ImageList_conversion end if arg.class == JPEG then jpeg_conversion end etc. etc. Rather I wanted my Binary_matrix object to check if the object to be converted to a Binary_matrix had a to_Binary_matrix method and then to call it. I also require all the Array methods for Binary_matrix because of the complex traversing and manipulation of the pixel data. To give a trivial example: does a black pixel in line n touch a black pixel in line n+1? What are the array ranges of a contiguous group of black pixels etc. Change a contiguous range of pixels to white (i.e. clear up noise) etc. Again because of complexity of the application I wanted to make the code as humanly readable as possible. So I want to be able to say page_in_pixels = page_image.to_Binary_matrix as well as page_in_pixels = Binary_matrix(page_image) (I know that may sound trivial but when you go back to look at your code a few months later, everything that makes it more easily readable helps.) So for those reasons the solution I came up with is as follows: (I'm not saying its necessarily a good solution and I really wish I could make it less clunky. if there was some way to tell whether method to_Binary_matrix was being called within the context of Binary_matrix initialize method or outside it then the flag -from_initialize_method- wouldn't be necessary) class A def to_Binary_matrix(from_initialize_method = false) if from_initialize_method return self else return Binary_matrix.new(self) end end ... end class Binary_matrix < Array def initialize(arg) called_from_initialize =true if arg.respond_to? :to_Binary_matrix arg = arg.to_Binary_matrix (called_from_initialize) else ....do some error reporting end validate arg #Is the Binary_matrix object correctly formed? end ... end -- Posted via http://www.ruby-forum.com/.