Created
September 10, 2016 05:41
-
-
Save amolpujari/5391d1d8d1638616e455685bc4ea89d2 to your computer and use it in GitHub Desktop.
flatten_my_array.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This is a custom method to flatten any given array | |
| # this is simple one to read and understand | |
| # by name it means to accept only array, so it is known that passing any other object than array will fail | |
| def flatten_my_array arr | |
| new_arr = [] | |
| arr.each do |element| | |
| if element.is_a? Array | |
| new_arr = new_arr.concat flatten_my_array(element) | |
| # know that Array#concat is faster way to concat two arrays in ruby | |
| else | |
| new_arr << element | |
| end | |
| end | |
| new_arr | |
| end | |
| flatten_my_array [[1,2,[3]],4] # => [1,2,3,4] | |
| flatten_my_array ['a', [1], { :key => [1,2,3]}, []] # => ["a", 1, {:key=>[1, 2, 3]}] | |
| flatten_my_array [] # => [] | |
| flatten_my_array nil # => NoMethodError | |
| flatten_my_array 123 # => NoMethodError | |
| flatten_my_array [[[[[1]]]]] # => [1] | |
| require 'benchmark' | |
| test_arr = [1,"str", [[[[[[[[[[[[[1]]]]]]]]]]]]]] | |
| puts Benchmark.measure { test_arr.flatten } | |
| # => 0.000000 0.000000 0.000000 ( 0.000035) | |
| puts Benchmark.measure { flatten_my_array test_arr } | |
| # => 0.000000 0.000000 0.000000 ( 0.000040) | |
| # flatten_my_array is a ruby function wherein Array#flatten is core ruby function in C, so it has to be faster than ruby one |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment