Ruby 配列からnilを削除するサンプル

環境
Windows11 pro 64bit
ruby 3.0.3p157

構文
# 元の配列は変わらない
配列.compact

# 元の配列変わります
配列.compact!
compactを使用して、配列からnilを削除します。

使用例1

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
arr = [ "s", nil, "t", nil, "c"]
p arr.compact
p arr
p arr.compact!
p arr
arr = [ "s", nil, "t", nil, "c"] p arr.compact p arr p arr.compact! p arr
arr = [ "s", nil, "t", nil, "c"]

p arr.compact

p arr

p arr.compact!

p arr

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
["s", "t", "c"]
["s", nil, "t", nil, "c"]
["s", "t", "c"]
["s", "t", "c"]
["s", "t", "c"] ["s", nil, "t", nil, "c"] ["s", "t", "c"] ["s", "t", "c"]
["s", "t", "c"]
["s", nil, "t", nil, "c"]
["s", "t", "c"]
["s", "t", "c"]

 

使用例2
rejectを使用して配列からnilを削除します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
arr = [ "s", nil, "t", nil, "u"]
p arr.reject{ |x| x.nil? }
p arr
p arr.reject!{ |x| x.nil? }
arr = [ "s", nil, "t", nil, "u"] p arr.reject{ |x| x.nil? } p arr p arr.reject!{ |x| x.nil? }
arr = [ "s", nil, "t", nil, "u"]

p arr.reject{ |x| x.nil? }


p arr

p arr.reject!{ |x| x.nil? }

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
["s", "t", "u"]
["s", nil, "t", nil, "u"]
["s", "t", "u"]
["s", "t", "u"] ["s", nil, "t", nil, "u"] ["s", "t", "u"]
["s", "t", "u"]
["s", nil, "t", nil, "u"]
["s", "t", "u"]

 

Ruby

Posted by arkgame