arraysrubycolorize

ruby shorter array iteration


I'm trying to find out if there is a shorter way to do the below code:

$my_array.each do |eh|
  row = Array.new
  eh.each do |k,v|
    if  k == 'state'
      if eh[k] ==  "stopped"
         row << eh[k].red
      elsif eh[k] ==  "running"
         row << eh[k].green
      else 
        row << eh[k].yellow
      end 
    else
     row << eh[k] 
    end 
  end 
  data << row 
end

The above is for the use of terminal-table and colorize


Solution

  • How about this:

    color_map = { 'stopped' => :red, 'running' => :green }
    data = $my_array.map do |eh|
      eh.map do |k,v|
        if  k == 'state'
          v.send color_map.fetch(v, :yellow)
        else
          v 
        end 
      end 
    end
    

    It uses map instead of each to avoid building the arrays manually. It also uses a hash to map the state to the colour instead of using if-statements.

    You could take it further and remove the inner if statement if you like, but this is at least an improvement.