Ruby 数组类drop_while()操作
Array#drop_while() : drop_while()是一个数组类方法,它可以按照特定的条件从数组中删除元素。
语法。 Array.drop_while()
参数:block – 要遵循的条件
返回:根据条件删除元素后的数组
代码#1:drop_while()方法的例子
# Ruby code for drop_while() method
# declaring array
a = [18, 22, 33, 100, 5, 6]
# declaring array
b = [1, 4, 1, 1, 88, 9]
# drop
puts "drop : #{a.drop_while {|x| x < 14}}\n\n"
# drop
puts "drop : #{b.drop_while{|x| x != 1}}\n\n"
输出:
drop : [18, 22, 33, 100]
drop : [4, 88, 9]
代码#2:drop_while()方法的例子
# Ruby code for drop_while() method
# declaring array
a = ["abc", "nil", "dog"]
# declaring array
b = ["cow", nil, "dog"]
# declaring array
c = ["cat", nil, nil]
# drop
puts "drop : #{a.drop_while {|x| x != "dog"}}\n\n"
# drop
puts "drop : #{b.drop_while{|x| x == "cow"}}\n\n"
输出:
drop : ["dog"]
drop : [nil, "dog"]