Ciechan
Ciechan

Reputation: 25

How to add string into Hash with each

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"

Upvotes: 1

Views: 817

Answers (2)

Glyoko
Glyoko

Reputation: 2080

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

Upvotes: 0

Zzz
Zzz

Reputation: 1703

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]

Upvotes: 3

Related Questions