I am working on building the flatten method in Ruby. Here is my code:
require 'byebug'
class Array
@@new_array = []
def new_flatten
self.each do |element|
if !element.is_a? Array
@@new_array << element
elsif element.is_a? Array
element.new_flatten
end
end
@@new_array
end
end
test_array = ([1,2,3,[4,5,6,[7]]])
puts test_array.new_flatten == test_array.flatten
My question is this. Do I need to use the class level variable? I would like to use an instance variable but it doesn't seem to get called when I do:
test_array = []
or
Array.new([])
So I had to create a class-level variable to hold the new flattened array.
The problem with using a class variable is that the same one is visible to all the instances, and
new_flatten
is an operation for an instance. You should refactor yournew_flatten
algorithm so it doesn't rely on what is, in effect, a "global" variable for the method calls.For example, you can use a local variable and Ruby's facility to append arrays with
+
:Also, as some tweaks of style, when doing an if-else, it's often clearer to state the positive logic first. And, you don't need the
elsif
in this case since theelse
is the complement of theif
. So rather than:It's clearer to say:
Your question is really confusing. In your title, you talk about calling
initialize
, but there is noinitialize
in your code. In your question, you talk about calling an instance variable, but you can't call variables, only methods.However, implementing
flatten
is just a simple fold, I don't see the need for storing any intermediate state: