From: Robert Klemme Date: 2010-09-15T01:51:37+09:00 Subject: Re: Converting from one class to another in Ruby On 14.09.2010 17:58, Harry Spier wrote: > Robert Klemme wrote: > >> Just do this for your classes: >> >> class A >> def initialize( what goes here? ) >> # what do you want to do here? >> end >> >> def to_binary_matrix >> bm = BinaryMatrix.new >> # fill bm >> bm >> end >> end >> >> >>> 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. >> >> Just call it (see below). >> > >> Why and what do you want to convert to BM in #initialize? This hasn't >> become clear yet. > > I wrote >>> 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 meant to write: (more finger trouble :-) ) Hopefully the trouble does not extend further up... :-) > I want to be able to do both: > page_in_pixels = page_image.to_Binary_matrix > page_in_pixels = Binary_matrix.new(page_image) > (i.e. Binary_matrix.new doesn't create an empty Binary_matrix object but > takes as a parameter an object which is converted to a Binary_matrix ) This seems quite backwards to me. What do you gain by this other than making the code more complicated than necessary? You say it feels awkward and still seem to insist on this approach. > so for that reason my solution had as follows: > 1) obj_a.to_Binary_matrix calls Binary_matrix.new to create a new > Binary_matrix object. > I.e.In this case #to_Binary_matrix is being called outside the context > of Binary_matrix#initialize > > but > > 2)Binary_matrix#initialize contains an arg = arg.to_Binary_matrix > statement to access the conversion logic. > I.e. #to_Binary_matrix is being called within the context of > Binary_matrix#initialize You can have it easier class A def to_binary_matrix bm = BinaryMatrix.new fill bm bm end def fill bm # do whatever it takes to make state of self # appear in bm end end class BinaryMatrix def initialize(x = nil) x.fill self rescue nil end end IIRC this is similar although not identical to what I have suggested in my first posting. But frankly, I find this only slightly less awkward. In my experience providing too many ways to do things is rather causing trouble than improving things. Plus, #to_x is a common idiom in Ruby to provide conversions of something into something else - in fact it is quite ubiquitous). > so my solution (retyped at the end of this post had a flag to keep from > getting in an infinite loop and to do the following: > > (I'm not sure if I'm missing something really obvious but I still don't > see that I don't need a flag or someway to tell if #to_Binary_matrix is > being called within Binary_matrix#initialize or not) See above. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/