1

I have a hash:

row = {
            'name' => '',
            'description' => '',
            'auth' => '',
            'https' => '',
            'cors' => '',
            'url' => ''
        }

and I also have an array:

["Cat Facts", "Daily cat facts", "No", "Yes", "No", "https://example.com/"]

How can I grab the array elements and set them as values for each key in the hash?

3 Answers 3

3

Let's say row is your hash and values is your array

row.keys.zip(values).to_h
 => {"name"=>"Cat Facts", "description"=>"Daily cat facts", "auth"=>"No", "https"=>"Yes", "cors"=>"No", "url"=>"https://example.com/"} 

It works if they are in the right order, of course

Sign up to request clarification or add additional context in comments.

Comments

2
h = { 'name'=>'',
      'description'=>'',
      'auth'=>'',
      'https'=>'',
      'cors'=>'',
      'url'=>'' }

arr = ["Cat Facts", "Daily cat facts", "No", "Yes", "No",
       "https://example.com/"]

enum = arr.to_enum
  #=> #<Enumerator: ["Cat Facts", "Daily cat facts", "No",
  #                  "Yes", "No", "https://example.com/"]:each>

h.transform_values { enum.next }
  #=> { "name"=>"Cat Facts",
  #     "description"=>"Daily cat facts",
  #     "auth"=>"No",
  #     "https"=>"Yes",
  #     "cors"=>"No",
  #     "url"=>"https://example.com/" }

See Hash#transform_values. Array#each can be used in place of Kernel#to_enum.

If arr can be mutated enum.next can be replaced with arr.shift.

Comments

0

Given the hash and the array:

row = { 'name' => '', 'description' => '', 'auth' => '', 'https' => '', 'cors' => '', 'url' => '' }
val = ["Cat Facts", "Daily cat facts", "No", "Yes", "No", "https://example.com/"]

One option is to use Enumerable#each_with_index while transforming the values of the hash:

row.transform_values!.with_index { |_, i| val[i] }
row
#=> {"name"=>"Cat Facts", "description"=>"Daily cat facts", "auth"=>"No", "https"=>"Yes", "cors"=>"No", "url"=>"https://example.com/"}

The bang ! changes the original Hash.

Comments

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.