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)