Welcome to Findnerd. Today we are going to discuss find functions in Ruby. There are different functions available. Please have a look.
A) find/detect : It will return either object or nil.
(0..10).find { |i| i == 5 }
# return 5
In above example we have a range from 0 to 10 and we are using find function for checking the number 5. You can also use find() with other mathematical operations. Please have a look.
(0..10).find { |i| i%3==0 }
return 3
In above example we are trying to detect numbers divisible with 3. This example is returning 3. It means, It is returning first matched number, there are three numbers in the range such as 3, 6, 9. You can also use detect() function in the same way. Please have a look.
(0..10).detect{ |i| (0..10).include?(i * 4) }
# return 0
In above example we are trying detect() function instead of find() function. We are checking current number multiple with 4, is included in the range or not.
B) find_all/select : In above examples if there are multiple values in result then find was returning only first number but if you want to return all the numbers then you need to use the find_all() function. Please have a look.
(0..10).find_all { |i| i%3==0 }
return [3,6,9]
Instead of using find_all() function you can also use the select() method. Please have a look.
(0..10).select{ |i| (0..10).include?(i * 4) }
# return [0,1,2]
In above example we are checking included number by multiple these numbers with 4.
This function will return array.
C) any? : It will return true or false as per the condition.
(0..10).any?{ |i| i==3 }
#return true
We are checking number 3 that is included in range or not. You can see, it returned true, it means it is included that number.
D) all? : This function is used to check whether your all mentioned numbers are included in the range or not.
(0..10).all?{ |i| i%3==0 }
#return false
You can see, all numbers in the range are not divisible by 3 so it is returning false.
E) delete_if: If we talk about the delete_if then it is used when you want to delete the numbers as per condition. Please have a look.
[*0..10].delete_if{ |i| i%3==0 }
# return [0,1,2,4,5,7,8,10]
Thank you for being with us!
1 Comment(s)