Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将键/值对转换为哈希_Ruby On Rails_Ruby_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 将键/值对转换为哈希

Ruby on rails 将键/值对转换为哈希,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,可能重复: 我有一个模型,它将键值对存储为另一个模型人的属性 将person.person\u属性转换为散列的简单方法是什么 这是我想出的一个愚蠢的方法: keys = person.person_attributes.map(&:key) values = person.person_attributes.map(&:value) hashed_attributes = Hash.new keys.each_index do |i| hashes_attribues[

可能重复:

我有一个模型,它将键值对存储为另一个模型人的属性

将person.person\u属性转换为散列的简单方法是什么

这是我想出的一个愚蠢的方法:

keys = person.person_attributes.map(&:key)
values = person.person_attributes.map(&:value)

hashed_attributes = Hash.new

keys.each_index do |i|
  hashes_attribues[keys[i]] = values[i]
end
有什么更优雅的方法可以做到这一点


提前谢谢,

您想将一组对象(每个对象都有
属性)转换成一个散列,其中
映射到

您可以使用以下命令,使用
Hash[array]
将二维数组转换为哈希:

Hash[person.person_attributes.map { |e| [e.key, e.value] }]
输入: 输出: 我喜欢这类东西

attributes = person.person_attributes.each_with_object({}) do |attribute, hash|
  hash[attribute.key] = attribute.value
end

如果您仍然使用Ruby 1.8.7,不用担心,.

可能是重复的,或者它不是完全重复的-我的理解是,只有一个数组(
person\u attributes
),我们需要从对该数组中的项调用的方法构建散列。根据操作代码判断,项不是散列。
{ :key1 => :value1, :key2 => :value2, :key3 => :value3 }
attributes = person.person_attributes.each_with_object({}) do |attribute, hash|
  hash[attribute.key] = attribute.value
end