1
x = "one two"
y = x.split

hash = {}

y.each do |key, value|
  hash[key] = value
end
print hash

The result of this is: one=> nil, two => nil

I want to make "one" - key, and "two" - value, but how to do this?

It may look like this: "one" => "two"

2 Answers 2

3

y is an array, therefore in the block key is the item itself ('one', 'two'), and value is always nil.

You can convert an array to hash using splat operator *

Hash[*y]

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

Comments

0

A bit faster way of doing it:

x="one two"
Hash[[x.split]]

If you're looking for a more general solution where x could have more elements, consider something like this:

hash = {}
x="one two three four"
x.split.each_slice(2) do |key, value| # each_slice(n) pulls the next n elements from an array
  hash[key] = value
end

hash

Or, if you're really feeling fancy, try using inject:

x="one two three four"
x.split.each_slice(2).inject({}) do |memo, (key, value)|
  memo[key] = value
  memo
end

1 Comment

Actually @Zhong Zheng's answer is more elegant. My solution's good if for some reason you're set on using each (or each_slice) methods and is perhaps useful for educational purposes, but in the real world Hash[*y] is cleaner.

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.