Ruby: How to use the 5 main Find methods within Code Blocks


/ Published in: Ruby
Save to your folder(s)

This shows how we can find objects inside code blocks (aka data sets).


Copy this code and paste it in your HTML
  1. #find / detect returns an Object or nil, it will not find all the numbers
  2. puts "\n" + "#find returns an Object or nil"
  3. puts (1..10).find { |i| i == 5 }
  4.  
  5. puts "\n" + "detect returns an Object or nil. Note:It only returns the first example."
  6. puts (1..10).detect { |i| i % 3 == 0 }
  7. puts "\n" + "detect can be used to determine which other numbers are within a range"
  8. puts (1..10).detect { |i| (1..10).include?(i * 3) }
  9.  
  10.  
  11. #find_all / select returns an Array
  12. puts "\n" + "find_all returns an Array"
  13. puts (1..10).find_all { |i| i % 3 == 0 }
  14.  
  15. puts "\n" + "select returns an Array. Three numbers can be multiplied by 3 and still not exceed 10."
  16. puts (1..10).select { |i| (1..10).include?(i * 3) }
  17.  
  18. # Method any? returns a Boolean
  19. puts "\n" + "any? returns a Boolean. In other words, are there any in the set that are true?"
  20. puts (1..10).any? { |i| i % 3 == 0 }
  21.  
  22. # Method all? returns a Boolean
  23. puts "\n" + "all? returns a Boolean. Do all the conditions meet the requirement?"
  24. puts (1..10).all? { |i| i % 3 == 0 }
  25.  
  26. # Method delete_if? returns an Array.
  27. puts "\n" + "delete_if anything is divisible by 3"
  28. puts [*1..10].delete_if { |i| i % 3 == 0 }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.