strange ruby behavior with a constant -
could explain me, why original constant list
beginning getting manipulated @ end? thought constant once initialized. want store manipulations in new array (new_list
) without affecting original 1 (list
).
$ned = "foo" $med = "" print list = [:nrd, :mrd_y] # -> [:nrd, :mrd_y] list = list new_list = list.delete_if { |element| case element when :nrd $ned.empty? when :mrd_y $ned.empty? || $med.empty? end } print new_list # -> [:nrd] print list # -> [:nrd] instead of [:nrd, :mrd_y]
array#delete_if
-> deletes every element of self block evaluates true.
$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 $ned.empty? when :mrd_y $ned.empty? || $med.empty? end }
list
, list
holding same array
object, object_id
tells above. each true
evaluation block delete_if
deletes item object referenced 84053120
. kept list
, list
. can use below:
$ned = "foo" $med = "" list = [:nrd, :mrd_y] list = list new_list = list.dup.delete_if { |element| case element when :nrd $ned.empty? when :mrd_y $ned.empty? || $med.empty? end } p new_list #=>[:nrd] p list #=>[:nrd, :mrd_y]
or (better approach use
array#reject
),
$ned = "foo" $med = "" list = [:nrd, :mrd_y] new_list = list.reject { |element| case element when :nrd $ned.empty? when :mrd_y $ned.empty? || $med.empty? end } p new_list #=>[:nrd] p list #=>[:nrd, :mrd_y]
Comments
Post a Comment