當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Ruby Array compact!()用法及代碼示例


Array#compact! ():緊湊! ()是一個Array類方法,該方法會在從數組中刪除所有“無”值元素(如果有)後返回數組。如果數組中沒有nil值,它將返回nil值。

用法: Array.compact!()

參數:  Array to remove the 'nil' value from. 

返回: removes all the nil values from the array.  nil - if there is no nil value in the array

代碼#1:Compact!()方法的示例

# Ruby code for compact!() method 
# showing how to remove nil values 
  
# declaring array 
a = [18, 22, 33, nil, 5, 6] 
  
# declaring array 
b = [5, 4, 1, 88, 9] 
  
# declaring array 
c = [18, 22, nil, 40, 50, 6] 
  
# removing nil value from array 
puts "removing nil value:#{a.compact!}\n\n"
  
# removing nil value from array 
puts "removing nil value:#{b.compact!}\n\n"
  
# removing nil value from array 
puts "removing nil value:#{c.compact!}\n\n"

輸出:


removing nil value:[18, 22, 33, 5, 6]

removing nil value:

removing nil value:[18, 22, 40, 50, 6]

代碼2:Compact!()方法的示例

# Ruby code for compact!() method 
# showing how to remove nil values 
  
# declaring array 
a = ["abc", "nil", "dog"] 
  
# declaring array 
b = ["cow", nil, "dog"] 
  
# declaring array 
c = ["cat", nil, nil] 
  
# removing nil value from array 
puts "removing nil value:#{a.compact!}\n\n"
  
# removing nil value from array 
puts "removing nil value:#{b.compact!}\n\n"
  
# removing nil value from array 
puts "removing nil value:#{c.compact!}\n\n"

輸出:

removing nil value:

removing nil value:["cow", "dog"]

removing nil value:["cat"]


相關用法


注:本文由純淨天空篩選整理自mayank5326大神的英文原創作品 Ruby | Array compact!() operation。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。