H
Harry Spier
Dear list members,
I have an application with a class Binary_matrix < Array (which is just
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
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
Thanks in advance,
Harry
I have an application with a class Binary_matrix < Array (which is just
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
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
Thanks in advance,
Harry