📜  红宝石 |数组 take_while()函数

📅  最后修改于: 2022-05-13 01:54:52.358000             🧑  作者: Mango

红宝石 |数组 take_while()函数

Array#take_while() : take_while()是一个 Array 类方法,它将元素返回到块,直到块返回 nil 或 false。

示例 #1:

# Ruby code for take_while() method
  
# declaring array
a = [18, 22, 33, 3, 5, 6]
  
# declaring array
b = [1, 4, 1, 1, 88, 9]
  
# declaring array
c = [18, 22, 3, 3, 50, 6]
  
# take_while
puts "take_while method : #{a.take_while {|num| num > 10 }}\n\n"
  
# take_while
puts "take_while method : #{b.take_while {|x| x.odd? }}\n\n"

输出 :

take_while method : [18, 22, 33]

take_while method : [1]

示例 #2:

# Ruby code for take_while() method
  
# declaring array
a = [18, 22, 33, 3, 5, 6]
  
# declaring array
b = [1, 4, 1, 1, 88, 9]
  
# declaring array
c = [18, 22, 3, 3, 53, 6]
  
# take_while
puts "take_while method : #{c.take_while {|num| num > 10 }}\n\n"
  
# take_while
puts "take_while method : #{c.take_while {|num| num.even? }}\n\n"

输出 :

take_while method : [18, 22]

take_while method : [18, 22]