In recent days I got chance to interview few candidates for the position of Ruby on Rails developer for a client. In the interview I asked few coding questions that I am willing to share with you guys. These are very basic questions but from the interview perspective very important as well.
We all know that ruby provided number of inbuilt methods for array to write our code in fast and simple manner. For example to get the minimum and maximum element from the ruby array you can simply use min and max methods rather then implementing these methods from scratch. And these are just examples, there are many such methods.
And one of such method is flatten.
The flatten method returns a new Array that is a recursive flattening of self. Where:
So the question I asked, was how to recreate the flatten method?
Now to solve this problem, let's think in algorithmic way:
Now let's start step by step:
Step 1: Define an array(that should not flattened already)
array = [1, 2, [3, 4, 5], [6, 7, [8, 9]], 10]
Step 2: Define the output variable(must be an empty array)s
results = []
However if you wish you can skip this step as well, as you can directly assign the method call output to results(see the step 4).
Stpe 3: Implement the method to flatten the array(the procedure)
def flattened_array(array, results = [])
array.each do |element|
if element.is_a?(Array)
# here we need to make recursive call to the flattened_array
# by checking if the current element is also an array
flattened_array(element, results)
else
results << element
end
end
results
end
Step 4: Returning the output(procedure execution)
results = flattened_array(array)
print results
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you wish you can verify the output by executing
array = [1, 2, [3, 4, 5], [6, 7, [8, 9]], 10]
array.flatten
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
And that's it. The recreation of flatten method is done.
You can see that this is a very basic and simple to solve problem but these problems covers multiple aspects of your skills like your algorithmic approach, thought process towards solving a problem, knowledge of programming elements like iterators, recursion, logic building and so on.
Try this at your end and wait for the next question.
Till then TATA, Good Bye.
Ruby on Rails is a very popular and most productive web application development framework. At APPSIMPACT Academy we provide best content to learn Ruby on Rails framework.