Rather than making class methods on Hash to create special hashes like
this, why not make subclasses, so you can attach specialized instance
methods that make sense only for these kinds of hashes. For instance,
for the Hash-of-Hashes form, you might want a method that “rotates”
the Hash into a new Hash-of-Hashes like this:
def rotate
res = HashOfHashes.new
each { |ok, ov| ov.each { |ik, iv| res[ik][ok] = iv } }
res
end
I agree that it would be nice to have them in the standard library,
but maybe Hash.of_hashes and Hash.of_arrays would be better names?
Yes, probably. I’m not religious about the names. My point was simply
that this is so often used that we might want to have it in the standard
library.
Where’s the point of the rescue clause? The error will show up much
later, i.e. after the method has returned.
Why would the error show later? It is just so one could pass a
immutable, like 0 to #with without raising an error b/c it doesn’t
respond to #dup.
The code block is not executed when you invoke Hash.with - hence there
can’t be an error. When you need it the rescue block is not there as
the block is called from a different context.
?
It’s closer than I initially thought. But: I wanted these two special
methods and not yet another generic method. For that, we have the
original Hash.new already. Your version still needs an argument. Since
I see that we are using an Array most of the time anyway that can be
coded into the method. No need for another generic approach IMHO.
It’s closer than I initially thought. But: I wanted these two special
methods and not yet another generic method. For that, we have the
original Hash.new already. Your version still needs an argument. Since
I see that we are using an Array most of the time anyway that can be
coded into the method. No need for another generic approach IMHO.
The difference between the existing and the new generic is the
assignment. I see the block form of new most often because some mutable
object should be assigned on read.
mfg, simon … l
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.