ruby-on-rails – 用于在1次操作中选择和拒绝2个数组的ruby数组(可枚举)方法

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 用于在1次操作中选择和拒绝2个数组的ruby数组(可枚举)方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. # this code works
  2. list = (0..20).to_a
  3. # => [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
  4.  
  5. odd = list.select { |x| x.odd? }
  6. # => [1,19]
  7.  
  8. list.reject! { |x| x.odd? }
  9. # => [0,20]
  10.  
  11. # but can i emulate this type of functionality with an enumerable method?
  12. set = [1,10]
  13. # => [1,10]
  14. one,five,ten = set
  15. # => [1,10]
  16. one
  17. # => 1
  18. five
  19. # => 5
  20. ten
  21. # => 10
  22.  
  23. # ------------------------------------------------
  24. # method I am looking for ?
  25. list = (0..20).to_a
  26. odd,even = list.select_with_reject { |x| x.odd? }
  27. # put the matching items into the first variable
  28. # and the non-matching into the second

解决方法

当然,你可以这样做:
  1. odd,even = list.partition &:odd?

猜你在找的Ruby相关文章