Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • find_all method in ruby.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 269
    Comment on it

    The find_all method has to do with arrays in Ruby.This method simply iterates through all the elements in an array and meanwhile test each of them against a test condition and finally returns an array containing all elements for which the test returned a true value.

    However ,we must note  that it uses a block to run that test condition .

    gauravjhadiyal@gauravjhadiyal:~$ irb
    2.1.5 :001 > ['x','y','z'].find_all {|element| element > 'z'}
     => [] 
    2.1.5 :002 > ['x','y','z'].find_all {|element| element < 'z'}
     => ["x", "y"] 
    2.1.5 :003 > ['x','y','z'].find_all {|element| element > 'a'}
     => ["x", "y", "z"] 
    2.1.5 :004 > ['x','y','z'].find_all {|element| element >= 'y'}
     => ["y", "z"] 
    

    If we are interested in finding out its internal working details ,please follow the below given pseudo code (bear in mind it isn't the actual implementation ) :

    class Array
     
       def find_all
         match_items = []
         self.each do |item|
            if yield(item)
              match_items << item      
            end   
         end
       end 
    
    end

    so ,in order to recapitulate it ,the find_all method passes each element to a block and test each of them  against the test condition  and depending on the result pushes them into a brand new array.

    Thanks for reading .

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: