Array#delete_if
-> 删除块计算为 true 的每个 self 元素。
$ned = "foo"
$med = ""
LIST = [:nrd, :mrd_y]
p LIST.object_id #=> 84053120
list = LIST
p LIST.object_id #=> 84053120
new_list = list.delete_if { |element|
case element
when :nrd then $ned.empty?
when :mrd_y then $ned.empty? || $med.empty?
end
}
List
并list
持有相同的Array
对象,object_id
如上所述。因此,对于来自块的每个true
评估,都会从delete_if
引用的对象中删除项目84053120
。由LIST
and保存list
。所以你可以使用以下内容:
$ned = "foo"
$med = ""
LIST = [:nrd, :mrd_y]
list = LIST
new_list = list.dup.delete_if { |element|
case element
when :nrd then $ned.empty?
when :mrd_y then $ned.empty? || $med.empty?
end
}
p new_list #=>[:nrd]
p LIST #=>[:nrd, :mrd_y]
或者(更好的方法使用Array#reject
),
$ned = "foo"
$med = ""
list = [:nrd, :mrd_y]
new_list = list.reject { |element|
case element
when :nrd then $ned.empty?
when :mrd_y then $ned.empty? || $med.empty?
end
}
p new_list #=>[:nrd]
p list #=>[:nrd, :mrd_y]