0

This is my first time using Ruby, and I need to use the inject method to create a hash from a given array. This code pretty closely mirrors several tutorials I've found, but get an undefined method `[]=' for nil:NilClass error when executing. Am I missing anything here?

def int_hash()
    [[:key1, "value1"], [:key2, "value2"]].inject({}) do |hash, element|
            hash[element.first] = element.last
            puts hash
    end
end

int_hash()
1
  • 1
    Though it's preferable to use Hash#to_h or Hash::[], you might consider writing what you have as ...do |hash, (k, v)| hash[k] = v... This makes use of array decomposition, which is a powerful and useful language feature. Commented Apr 12, 2021 at 5:15

1 Answer 1

1

Since puts is the last statement in the block and it returns nil, nil is returned causing the accumulator hash to be nil in the second iteration. You should return the hash. And you should pass the array as an argument to the inj_hash method to make it reusable.

def inj_hash(arr)
  arr.inject({}) do |hash, element|
    hash[element.first] = element.last
    hash
  end
end

inj_hash([[:key1, "value1"], [:key2, "value2"]])
#=> {:key1=>"value1", :key2=>"value2"}

The simplest solution to create a hash from an array of key-value pairs is to use Hash::[].

arr = [[:key1, "value1"], [:key2, "value2"]]
Hash[arr]
#=> {:key1=>"value1", :key2=>"value2"}
Sign up to request clarification or add additional context in comments.

2 Comments

Or switch to Hash#merge! ([[:key1, "value1"], [:key2, "value2"]].inject({}) { |hash, element| hash.merge!(element.first => element.last) }) or even Array#to_h ([[:key1, "value1"], [:key2, "value2"]].to_h). But this looks like an Enumerable#inject exercise so your first one of my merge! version are probably the most appropriate.
If you want debug output, you can use p hash. As opposed to puts it returns the passed argument(s).

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.