0

I have the following hash from a json decode:

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

I basically want to change the roles value to be in a comma delimited sentence like doing value.to_sentence. How do I achieve this?

2
  • Can you clarify? Do you want to turn ["accounting", "sales"] into "accounting, sales"? Commented Feb 23, 2012 at 3:05
  • Yes that what I'm trying to do. Commented Feb 23, 2012 at 3:42

2 Answers 2

2

Try this:

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

[Edit] For example:

h = {"person"=>{"user"=>[{"username"=>"foo", "status"=>"Y", "roles"=>["accounting", "sales"]}]}}
fix_roles(h)
h # => {"person"=>{"user"=>[{"username"=>"foo", "status"=>"Y", "roles"=>"accounting, sales"}]}}
Sign up to request clarification or add additional context in comments.

4 Comments

I get TypeError: can't convert String into Integer
@oprogfrogo: if you copy your hash into a variable, say "h" and call "fix_roles(h)" then your hash will be modified as you describe.
Thanks for getting back to me. That works with the first element in the array. How can I make it update when there are multiple elements. Like this: h = {"person"=>{"user"=>[{"username"=>"foo", "status"=>"Y", "roles"=>["accounting", "sales"]}, {"username"=>"bar", "status"=>"Y", "roles"=>["customer service", "sales"]}]}}
Thanks for showing the path. I've figured out how to iterate through it and it works now:
1

Thanks to maerics example, I was able to achieve the solution by iterating through each array element:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.