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
    • 915
    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 .

    1. gauravjhadiyal@gauravjhadiyal:~$ irb
    2. 2.1.5 :001 > ['x','y','z'].find_all {|element| element > 'z'}
    3. => []
    4. 2.1.5 :002 > ['x','y','z'].find_all {|element| element < 'z'}
    5. => ["x", "y"]
    6. 2.1.5 :003 > ['x','y','z'].find_all {|element| element > 'a'}
    7. => ["x", "y", "z"]
    8. 2.1.5 :004 > ['x','y','z'].find_all {|element| element >= 'y'}
    9. => ["y", "z"]
    10.  

    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 ) :

    1. class Array
    2. def find_all
    3. match_items = []
    4. self.each do |item|
    5. if yield(item)
    6. match_items << item
    7. end
    8. end
    9. end
    10.  
    11. 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
Reset Password
Fill out the form below and reset your password: