Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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重构数据_Ruby_Arrays - Fatal编程技术网

Ruby重构数据

Ruby重构数据,ruby,arrays,Ruby,Arrays,我需要构建一个哈希数组,如下所示: [ {:name=>"company", :value=>"Microsoft"}, {:name=>"type", :value=>"software"}, {:name=>"country", :value=>"US"}, {:name=>"valid", :value=>"yes"} ] def build(attributes=[]) list = [] attributes.each {|k

我需要构建一个哈希数组,如下所示:

[
{:name=>"company", :value=>"Microsoft"}, 
{:name=>"type", :value=>"software"}, 
{:name=>"country", :value=>"US"}, 
{:name=>"valid", :value=>"yes"}
]
def build(attributes=[])
 list = []
 attributes.each {|k,v| list.push({:name=> "#{k}", :value=> "#{v}"})}
 list
end
我不必一直定义名称和值字段,而是构建了一个助手函数,如下所示:

[
{:name=>"company", :value=>"Microsoft"}, 
{:name=>"type", :value=>"software"}, 
{:name=>"country", :value=>"US"}, 
{:name=>"valid", :value=>"yes"}
]
def build(attributes=[])
 list = []
 attributes.each {|k,v| list.push({:name=> "#{k}", :value=> "#{v}"})}
 list
end
然后,我可以简单地创建如下数组:

attribs = { :company => 'Microsoft', :type => 'software', :country=> 'US', :valid=> 'yes'}
puts build(attribs).inspect

#[{:name=>"company", :value=>"Microsoft"}, {:name=>"type", :value=>"software"}, {:name=>"country", :value=>"US"}, {:name=>"valid", :value=>"yes"}]
对于Ruby来说,这似乎有点低效和冗长!有没有更干净或更有效的方法来实现这一结果

问候,


Carlskii

我假设属性具有以下类型的数据:

attributes = [['company','Microsoft'],...]
然后,要从中构建哈希,请执行以下操作:

attributes.map { |k,v| {:name => k, :value => v} }
#=> [{:name=>"company", :value=>"Microsoft"},...
您还可以使用Ruby的方法,该方法接受偶数个参数作为键值对:

Hash['company', 'microsoft','type','software','country','us']
#=> {"company"=>"microsoft", "type"=>"software", "country"=>"us"}
这通常与Ruby的splat操作符结合使用,它允许您将数组作为方法参数传递

attributes = ['company', 'microsoft','type','software','country','us']
Hash[*attributes]
#=> {"company"=>"microsoft", "type"=>"software", "country"=>"us"}

该结构看起来非常像对象状态的表示形式:name的值始终是同一个集合,还是需要处理运行时变化?不,很遗憾,我需要处理运行时变化!太好了我认为Ruby会提供一种更干净的方法来实现这一点。谢谢