1

I have an array of strings of this format ['config = 3', 'config_b.root.a.b.c = 13'] ; my goal is to create the following json object from them

  {
    "config": 3,
    "config_b": {
      "root": {
        "a": {
          "b": {
            "c": 13
          }
        }
      }
    }
  }

this is my current working approach


# inputs is an array of strings
def create_config(inputs)
  hash={}
  inputs.each do |x|
    value = x.split("=")[1]
    keys = x.split("=")[0].strip.split(".")
    add_item(keys,value,hash)
  end
  print hash
end

# recusive function for adding items
def add_item(keys,value,hash)
  current = keys.shift
  if keys.empty?
    hash[current] = value
  else
    hash[current] = {}
    add_item(keys,value,hash[current])
  end
end

I would like to know if anyone has a better approach for solving this, Thanks

0

1 Answer 1

3

I think I have a solution.

def create_config(inputs)
  inputs.map do |e|
    keys, value = e.split(' = ')
    keys.split('.').reverse.inject(value) { |assigned_value, key| { key => assigned_value } }
  end.reduce(:merge)
end

I tried it with

['config = 3', 'config_b.root.a.b.c = 13']

and got

{"config"=>"3", "config_b"=>{"root"=>{"a"=>{"b"=>{"c"=>"13"}}}}}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, @Alexey but I think your approach works only for a single input and not for an array of strings
Run this method for each array string, and then merge the resulting hashes together.
@TrésorBireke it is even simpler then. I have updated the method
Very interesting approach @AlexeySchepin
@TrésorBireke let me know if you want better explanation how it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.