Quantcast
Viewing latest article 13
Browse Latest Browse All 42

Overriding a hash and making [] operators private - cant use ||= anymore

Test code:

class PrivHash < Hash  def set(key, val)     self[key] = val  end  def set_maybe(key, val)    self[key] ||= val  end  private  def []= key, value   end  def [] key    super              endend

With this code, I expect both set and set_maybe to work. However, only set works and set_maybe fails with:

[30] pry(#<TranslationInfo>):1> ph.set_maybe(:a, 1)NoMethodError: private method `[]' called for {:a=>2}:#Class:0x007f99c5924c38>::PrivHash from (pry):56:in `set_maybe'

I assumed that self[:b] ||= <x> is just syntactic sugar for self[:b] || self[:b] = <x>, but I guess it isn't because this works.

What bugs me is why I am getting this error.. I am executing this from within the class so why am I getting private method error?


Viewing latest article 13
Browse Latest Browse All 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>