Hash.delete_if {| key value | true} does not delete ... why?

I am working on the act_as_taggable_on plugin, but there is something that I cannot understand (even if it's just a very simple line of code).

puts "before:" + cache.inspect
# cache.delete_if {| key, value | key.id == owner.id && key.class == owner.class} # original code line
cache.delete_if {| key, value | true} # my test code
puts "after:" + cache.inspect

# output
before: {#<TaggableUser id: 1, name: nil>=>["dog"]}
after: {# TaggableUser id: 1, name: nil>=>["dog"]}

My problem is that cache.delete_if doesn't delete anything, even if it always evaluates to true. I just don’t understand why ... and really tried a lot. This is just a hash cache issue. But I really could not find anything special in this particular hash.

The cache is created in this method:

def cached_owned_tag_list_on (context)
  variable_name = "@owned _ # {context} _list"
  cache = instance_variable_get (variable_name) || instance_variable_set (variable_name, {})
end

The full code can be viewed here (see line 60): http://github.com/mbleigh/acts-as-taggable-on/blob/master/lib/acts_as_taggable_on/acts_as_taggable_on/ownership.rb#L60

One more step

When I make rehashup delete_if, it's working. What can “spoil” a hash in such a way that it is necessary to rephrase it before any deletions are performed?

+3
source share
3 answers

From the documentation rehash:

 call-seq:
   hsh.rehash -> hsh

 Rebuilds the hash based on the current hash values for each key. If
 values of key objects have changed since they were inserted, this
 method will reindex <i>hsh</i>. 

, ( ActiveRecord) . AR:

# File activerecord/lib/active_record/base.rb, line 1613
1613:       def hash
1614:         id.hash
1615:       end

, . ? , , , , ( id ).

, : nil, , - , .

+4

, cache Hash? , , .

$ ruby -v
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]

>> h = {:a => 1, :b => 2}
=> {:b=>2, :a=>1}
>> h
=> {:b=>2, :a=>1}
>> h.delete_if {|k,v| v == 2}
=> {:a=>1}
>> h
=> {:a=>1}

>> h = {:a => 1, :b => 2}
=> {:b=>2, :a=>1}
>> h.delete_if {|k,v| true}
=> {}
>> h
=> {}
+2

Maybe this is actions_as_taggable_on error, and you can just fill out the error report.

0
source

Source: https://habr.com/ru/post/1772214/


All Articles