Ruby - 更改数组的值哈希值

时间:2012-02-23 02:56:56

标签: ruby

我有一个来自json decode的以下哈希:

  

{“person”=> {“user”=> [{“username”=>“foo”,“status”=>“Y”,   “roles”=> [“accounting”,“sales”]}]}}

我基本上想要将角色值更改为逗号分隔的句子,例如执行value.to_sentence。我如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

试试这个:

def fix_roles(h)
  user0 = h['person']['user'][0]
  user0['roles'] = user0['roles'].join(', ')
end

[编辑] 例如:

h = {"person"=>{"user"=>[{"username"=>"foo", "status"=>"Y", "roles"=>["accounting", "sales"]}]}}
fix_roles(h)
h # => {"person"=>{"user"=>[{"username"=>"foo", "status"=>"Y", "roles"=>"accounting, sales"}]}}

答案 1 :(得分:1)

感谢maerics示例,我能够通过迭代每个数组元素来实现解决方案:

def fix_roles(w)
  w['person']['user'].each do |arr|
    arr.each do |k,v|
      arr['roles'] = v.join(', ') if k == 'roles' 
    end
  end
end