• accessing a nested ruby hash knowing the path to

    From Mario Ruiz@21:1/5 to All on Thu Jan 4 08:04:43 2018
    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!

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Robert Klemme@21:1/5 to Mario Ruiz on Fri Jan 5 08:24:00 2018
    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/

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)