如何将字符串添加到哈希中

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

结果是:一=>无,二=>无

我想制作 "one" - 键,以及 "two" - 值,但该怎么做?

它可能看起来像这样:"one" => "two"

y 是一个数组,因此块中的 key 是项目本身('one'、'two'),并且值始终为 nil。

您可以使用 splat 运算符将数组转换为散列 *

Hash[*y]

更快的方法:

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

如果您正在寻找一个更通用的解决方案,其中 x 可以包含更多元素,请考虑这样的事情:

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

或者,如果您真的很喜欢,请尝试使用注入:

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