I have a JSON file with parsed data stored in a @colors instance variable, as follows:
[{:color=>"red", :value=>"#f00"} {:color=>"green", :value=>"#0f0"} {:color=>"blue", :value=>"#00f"} {:color=>"cyan", :value=>"#0ff"} {:color=>"magenta", :value=>"#f0f"} {:color=>"yellow", :value=>"#ff0"} {:color=>"black", :value=>"#000"}]
Now I want to iterate through this output to create a table in a view where there is
<tr><td>color</td><td>value</td></tr>
When I derive another instance variable like this —
@even_colors = @colors.values_at(* @colors.each_index.select {|i| i.even?}).map(&:values)
I get an array of arrays consisting of every other color/value pair
[["red", "#f00"], ["blue", "#00f"], ["magenta", "#f0f"], ["black", "#000"]]
But what I want to create two separate arrays, one consisting only of the color names indicated by :color (red, blue, etc.) and the other consisting of just the hexs indicated by :value (#f00, #00f, etc.). I can’t seem to figure out how to do that. Anyone have any suggestions? Thanks …
You could do it with two passes through
@colors:Or you could it with on pass:
then look at
parts[:names]for the color names andparts[:hexes]for the hex values.I don’t really see why you want to split
@colorsup though, you could produce your table straight from@colors:Breaking
@colorsinto two arrays seems like busy-work to me.