How do I run a series of hashes inside an array and verify its contents?

0

Good afternoon friends of stackoverflow.

I have my next question in rails I have the following hash inside an array. @permissions_crud_hash = [:name => name_, :c => c, :r => r, :u => u, :d => d] @permissions_crud.push @permissions_crud_hash which has something like that as an example.

[{:name=>["Administracion"], :c=>[true], :r=>[true], :u=>[false], :d=>[false]}], [{:name=>["Permisos"], :c=>[true], :r=>[true], :u=>[true], :d=>[true]}]]

What I want to know is how to get out of that hash every example value I want to take if there is a name of "Permissions" inside that hash and each value such as c, r, u, d.

An example that I try to do but does not give me is this.

      if @permissions_crud.include?(['Permisos'])

      if '@permissions_crud.include?(['Permisos'][:c=>true])'

Thank you very much.

    
asked by Tysaic 31.01.2018 в 15:15
source

1 answer

0

It seems that your array is more nested than it should be and, to be a valid array, you need a [ , so the array would look like this:

[
    [{:name=>["Administracion"], :c=>[true], :r=>[true], :u=>[false], :d=>[false]}],
    [{:name=>["Permisos"], :c=>[true], :r=>[true], :u=>[true], :d=>[true]}]
]

Considering that structure, you could get the value by first using flatten to remove the extra layer from the array (ie converting it into an array of hashes instead of a fix of arrays ) and then use find ; for example:

permisos = @permissions_crud.flatten.find { |p| p[:name] == ["Permisos"] }
#=> {:name=>["Permisos"],:c=>[true],:r=>[true],:u=>[true],:d=>[true]} 

And to obtain each value, simply consult the key you are looking for directly in the hash that you just obtained; for example:

permisos[:c]
#=> [true]

If you have control over the arrangement I would recommend simplifying it by removing all the extra layers which seem unnecessary, leaving your structure simpler:

[
    { :name=>"Administracion", :c=>true, :r=>true, :u=>false, :d=>false }, 
    { :name=>"Permisos", :c=>true, :r=>true, :u=>true, :d=>true }
]

To obtain the values, the process would be practically the same, but without flatten and with the benefit of obtaining the final value instead of an array (e. true instead of [true] ):

permisos = @permissions_crud.find { |p| p[:name] == "Permisos" }
#=> {:name=>"Permisos",:c=>true,:r=>true,:u=>true,:d=>true}

permisos[:c]
#=> true
    
answered by 31.01.2018 / 17:04
source