Ruby:如何在代码块中使用5个主要的Find方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby:如何在代码块中使用5个主要的Find方法相关的知识,希望对你有一定的参考价值。

This shows how we can find objects inside code blocks (aka data sets).
  1. #find / detect returns an Object or nil, it will not find all the numbers
  2. puts " " + "#find returns an Object or nil"
  3. puts (1..10).find { |i| i == 5 }
  4.  
  5. puts " " + "detect returns an Object or nil. Note:It only returns the first example."
  6. puts (1..10).detect { |i| i % 3 == 0 }
  7. puts " " + "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 " " + "find_all returns an Array"
  13. puts (1..10).find_all { |i| i % 3 == 0 }
  14.  
  15. puts " " + "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 " " + "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 " " + "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 " " + "delete_if anything is divisible by 3"
  28. puts [*1..10].delete_if { |i| i % 3 == 0 }

以上是关于Ruby:如何在代码块中使用5个主要的Find方法的主要内容,如果未能解决你的问题,请参考以下文章

在 Ruby 块中使用“返回”

Ruby 2.5 的十个新特性

如何在 Ruby 的 MULTI 块中读取 Redis?

Ruby - 即使抛出了 Stripe 异常,else 块中的代码也会执行

有人可以解释 Ruby 在块中使用管道字符吗?

在 Ruby gsub 块中使用命名的捕获组(正则表达式)