joeyk16 joeyk16 - 2 months ago 7
Ruby Question

Convert Hash Into And Array Of Strings

{"offer:manage_all"=>["0", "1"], "offer:index"=>["0"], "offer:new"=>["0"], "offer:show"=>["0"], "offer:create"=>["0"], "offer:update"=>["0"], "offer:destroy"=>["0"], "job:manage_all"=>["0", "1"], "job:index"=>["0", "1"], "job:new"=>["0"], "job:create"=>["0"], "job:edit"=>["0"], "job:update"=>["0"], "job:destroy"=>["0"], "user:manage_all"=>["0", "1"], "user:index"=>["0"], "user:new"=>["0"], "user:create"=>["0"], "user:edit"=>["0"], "user:update"=>["0"], "user:destroy"=>["0"], "account_access:manage_all"=>["0", "1"], "role:manage_all"=>["0", "1"], "role:index"=>["0"], "role:new"=>["0"], "role:create"=>["0"], "role:edit"=>["0"], "role:update"=>["0"], "role:destroy"=>["0"], "welcome_package:manage_all"=>["0", "1"]}


I need to convert this hash into a string.

If the key has a value of 1 the key needs to be pushed to a an array.

The above will has will need to equal this because they are the keys with a value that includes 1.

["offer:manage_all", "job:manage_all", "job:index", "account_access:manage_all", "role:manage_all", "welcome_package:manage_all"]


Thank you in advance.

Answer

try method select and keys

hash = {"offer:manage_all"=>["0", "1"], "offer:index"=>["0"], "offer:new"=>["0"], "offer:show"=>["0"], "offer:create"=>["0"], "offer:update"=>["0"], "offer:destroy"=>["0"], "job:manage_all"=>["0", "1"], "job:index"=>["0", "1"], "job:new"=>["0"], "job:create"=>["0"], "job:edit"=>["0"], "job:update"=>["0"], "job:destroy"=>["0"], "user:manage_all"=>["0", "1"], "user:index"=>["0"], "user:new"=>["0"], "user:create"=>["0"], "user:edit"=>["0"], "user:update"=>["0"], "user:destroy"=>["0"], "account_access:manage_all"=>["0", "1"], "role:manage_all"=>["0", "1"], "role:index"=>["0"], "role:new"=>["0"], "role:create"=>["0"], "role:edit"=>["0"], "role:update"=>["0"], "role:destroy"=>["0"], "welcome_package:manage_all"=>["0", "1"]}

keys = hash.select{ |key,val| val.include? "1" }.keys

#=> ["offer:manage_all", "job:manage_all", "job:index", "user:manage_all", "account_access:manage_all", "role:manage_all", "welcome_package:manage_all"]
Comments