So the hashes created would go by the names hash1, hash2, hash3…
Does anyone know how to do that?
As other posters have mentioned, it’s quite possible you don’t want to
do that, but instead want an Array or Hash of Hashes to allow you to
more easily access the individual Hashes.
However, that’s not as fun as exploring the possibilities You could
use Object#instance_variable_set, but then you’d have @hash1, @hash2, … instead of hash1, hash2, …
Using Kernel#eval e.g. eval "hash1={:key=>value}; … " won’t work
because as of Ruby 1.8, you’re required to define local variables in
the outer scope prior to executing eval which would defeat the
purpose.
However, I noticed Kernel#eval accepts a binding parameter, so the
following may do what you thought you wanted to do (but probably don’t
actually want to do):
eval (1…10).inject(“”) {|m,o| m << “hash#{o}={:key =>
‘value#{o}’};” }, binding
Brian A.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.