- Nov 2022
-
github.com github.com
-
by using symbols as keys, you will be able to use the implicit conversion of a Mash via the #to_hash method to destructure (or splat) the contents of a Mash out to a block
Eh? The example below:
symbol_mash = SymbolizedMash.new(id: 123, name: 'Rey') symbol_mash.each do |key, value| # key is :id, then :name # value is 123, then 'Rey' end
seems to imply that this is possible (and does an implicit conversion) because it defines
to_hash
. But that's simply not true, as these 2 examples below prove:``` main > symbol_mash.class_eval { undef :to_hash } => nil
main > symbol_mash.each {|k,v| p [k,v] } [:id, 123] [:name, "Rey"] => {:id=>123, :name=>Rey} ```
``` main > s = 'a' => a
main > s.class_eval do def to_hash chars.zip(chars).to_h end end => :to_hash
main > s.to_hash => {a=>a}
main > s.each Traceback (most recent call last) (filtered by backtrace_cleaner; set Pry.config.clean_backtrace = false to see all frames): 1: (pry):85:in
__pry__' NoMethodError: undefined method
each' for "a":String ```
-