Dynamically reading this keys values from json file

Hi i have one array of hash path below
userpath = [“data”,“paging”,“next”]
the above path i want in below formate,
hash[“data”][“paging”][“next”]

please help me how can i achieve this

Here’s a thought I am jotting down:

Read the file, store the file’s modification time in a variable (you can use File#ctime for that). Parse the JSON formatted file. Next, in an infinite loop (with a small sleep of 0.125 to 0.25 seconds maybe) running in a Thread, read the file’s modification time constantly. When the modification time is newer than the time stored in the variable, read the JSON file again, and re-parse it… That way when the JSON file is changed, the program automatically updates itself…

I think he’s trying to dynamically access a deeply nested hash.

You can use the dig method.

[14] pry(main)> userpath = ["a", "b", "c"]
=> ["a", "b", "c"]
[15] pry(main)> hash = { "a" => { "b" => { "c" => "value" }}}
=> {"a"=>{"b"=>{"c"=>"value"}}}
[16] pry(main)> hash.dig *userpath
=> "value"
2 Likes

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

Sponsor our Newsletter | Privacy Policy | Terms of Service