Search code examples
arraysrubyhashkey-value

Converting array of stringified key value pairs to hash in Ruby


I have some key-value pair strings in an array:

array = [ "Name = abc", "Id = 123", "Interest = Rock Climbing" ]

I need to convert it to a hash:

hash = { "Name" => "abc", "Id" => "123", "Interest" => "Rock Climbing" }

I must be doing something wrong because I'm getting weird mappings with my .shift.split resulting in {"Name=abc"=>"Id=123"}.


Solution

  • All you need to do is split each part of the array into a key and value (yielding an array of two-element arrays) and then pass the result to the handy Hash[] method:

    arr = [ "Name = abc", "Id = 123", "Interest = Rock Climbing" ]
    
    keys_values = arr.map {|item| item.split /\s*=\s*/ }
    # => [ [ "Name", "abc" ],
    #      [ "Id", "123" ],
    #      [ "Interest", "Rock Climbing" ] ]
    
    hsh = Hash[keys_values]
    # => { "Name" => "abc",
    #      "Id" => "123",
    #      "Interest" => "Rock Climbing" }