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"
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
Hash[*y] is cleaner.