Ruby 集合 delete()函数
delete() 是Ruby中的一个内置方法,它从集合中删除给定的对象并返回self对象。在对象不存在的情况下,它只返回自己。
语法 : s1.name.delete(object)
参数 :该函数需要一个必须的参数,即要删除的对象。
返回值 : 从集合中删除对象后,它将返回 self。
例子 1 :
#Ruby program to illustrate the
#delete method
#requires the set
require "set"
s1
= Set[1, 2, 3]
#deletes 2 and prints self
puts s1.delete(2)
#deletes 1 and prints self
puts s1.delete(1)
#deletes 4 and prints self
puts s1.delete(4)
输出:
Set: {1, 3}
Set: {3}
Set: {3}
例2 :
#Ruby program to illustrate the
#delete method
#requires the set
require "set"
s1
= Set[11, 12, 33, "a"]
#deletes 'a' and prints self
puts s1.delete("a")
#deletes 11 and prints self
puts s1.delete(11)
#deletes 33 and prints self
puts s1.delete(33)
输出:
Set: {11, 12, 33}
Set: {12, 33}
Set: {12}
参考资料 : https://devdocs.io/ruby~2.5/set#method-i-delete