Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #7378
| From | Robert Klemme <shortcutter@googlemail.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: accessing a nested ruby hash knowing the path to |
| Date | 2018-01-05 08:24 +0100 |
| Message-ID | <fb8nghFtq5lU1@mid.individual.net> (permalink) |
| References | <e9acfcf2-1f5f-45f1-a59c-dc63614c17fa@googlegroups.com> |
On 04.01.2018 17:04, Mario Ruiz wrote:
> 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
You should start by storing your paths not as String but as Array of
actual key types (Symbol and Fixnum in this case). Then you can easily
use #inject without any risks of eval.
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
Back to comp.lang.ruby | Previous | Next — Previous in thread | Find similar
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