红宝石 |设置divide()函数
divide()是 Ruby 中的一个内置方法,它返回一组集合。它根据块给出的条件进行划分。如果它们不满足给定条件,则将它们分成单个元素。
Syntax: s1.divide(condition)
Parameters: The function takes the condition on which the set is to be divided into sets of set.
Return Value: It returns a new set built by duplicating the set, removing every element that appears in the given enumerable object.
示例 1 :
# Ruby program to illustrate the divide method
# requires the set
require "set"
s1 = Set[8, 5, 4]
# divide method used
puts s1.divide { |i,j| (i - j).abs == 3 }
输出:
Set: {#Set: {8, 5}, #Set: {4}}
示例 2 :
# Ruby program to illustrate the divide method
# requires the set
require "set"
s1 = Set[16, 8, 3, 5, 2]
# divide method used
puts s1.divide { |i,j| (i - j)%2 == 0 }
输出:
Set: {#Set: {16, 8, 2}, #Set: {3, 5}}