ruby 中数组的一些应用 兰猫

简单的include? 用法, 验证是否存在元素

[[1,2], 'Dog', 'Bird'].include? [1,2,3] => false
[[1,2], 'Dog', 'Bird'].include? [1,2] => true

  

数组子集的判断

方法一:
arger_array = [1,2,3,4,5,6]
smaller_array = [4,1]
smaller_array.all? {|smaller_array_item| larger_array.include?(smaller_array_item)}
方法二:
[1,2,4,6].all?{|i| [1,2,3,4,5,7].include?(i)} #=> false
[1,2,4].all?{|i| [1,2,3,4,5,7].include?(i)} #=> true
方法三:
class Array
 
def subset?(a)
   
(self - a).length == 0
 
end
end
class Array
 
def subset?(a)
   
(self & a).length == length
 
end
end
class Array
 
def subset?(a)
   
(self & a) == a
 
end
end

  再链接一个网上的blog  http://www.cnblogs.com/lexus/archive/2010/12/18/1909928.html

真子集和子集举例
子集比真子集范围大,子集里可以有全集本身,真子集里没有,还有,要注意非空真子集与真子集的区别,前者不包括空集,后者可以有。
比如全集I为{1,2,3},
它的子集为{1}、{2}、{3}、{1,2}、{1,3}、{2,3}、{1,2,3}、再加个空集;
而真子集为{1}、{2}、{3}、{1,2}、{1,3}、{2,3}、再加个空集,不包括全集I本身。
非空真子集为{1}、{2}、{3}、{1,2}、{1,3}、{2,3},不包括全集I及空集。
设全集I的个数为n,它的子集个数为2的n次方,真子集的个数为2的n次方-1,非空真子集的个数为2的n次方-2。
 

Add subset and superset operator for Array

class Array
 
  def subset?(other)
    self.each  do |x|
      if !(other.include? x)
        return false
      end
    end
    true
  end
 
  def superset?(other)
    other.subset?(self)
  end
 
end
 
a = [1, 2, 3, 4]
b = [2, 3]
c = [2, 3, 4, 5]
 
flag1 = c.subset? a     # false
flag2 = b.subset? a     # true
flag3 = c.superset? b   # true
 
 
require "set"
a=[1,2,3]
as=a.to_set
b=[1,2]
bs=b.to_set
bs.subset?(as)=>true

  

原文地址:https://www.cnblogs.com/ilazysoft/p/2172359.html