Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #7377

accessing a nested ruby hash knowing the path to

Newsgroups comp.lang.ruby
Date 2018-01-04 08:04 -0800
Message-ID <e9acfcf2-1f5f-45f1-a59c-dc63614c17fa@googlegroups.com> (permalink)
Subject accessing a nested ruby hash knowing the path to
From Mario Ruiz <tcblues@gmail.com>

Show all headers | View raw


Let's guess I have a hash like this:
my_hash={
    loginame: :"pepe",
    name: :"Duuuo",
    zip: {default: '00000', correct: :'54666'},
    city: {
        uno: "1",
        dentro: {
            default: "Madrid",
            original: "Barcelona"
        }

    },
    accent: [
      10,
      20,
      {
        original: "spanish",
        learned: "german"
      }
    ]
}

And we have an array of unknown paths to the values in the hash, for example:
keys=[
  "[:city][:dentro][:original]",
  "[:accent][1]",
  "[:accent][2][:original]"
]


And I want to know the value in the hash on that path, for that purpose I am using in my code 'eval' 

keys.each{|key|
  puts eval "my_hash#{key}"
}


But apart of not being elegant... there are many risks, so I would like to know if you propose any other better way

Thanks!

Back to comp.lang.ruby | Previous | NextNext in thread | Find similar


Thread

accessing a nested ruby hash knowing the path to Mario Ruiz <tcblues@gmail.com> - 2018-01-04 08:04 -0800
  Re: accessing a nested ruby hash knowing the path to Robert Klemme <shortcutter@googlemail.com> - 2018-01-05 08:24 +0100

csiph-web