Gleydson S. Tavares Gleydson S. Tavares - 4 months ago 7
Ruby Question

how to change the color of a String class

I created a method to modify the colors of the String class, but I can not. The following code:

class String
@colors_hash = { red: 31, green: 32, yellow: 33, blue: 34, pink: 35, light_blue: 94, white: 97, light_grey: 37, black: 30 }

def self.create_colors
@colors_hash.each do |key, value|
self.class_eval("def #{key}; '\e[#{value}m #{self} \e[0m'; end")
end
end

end


When I do, "Gleydson".red

it returns "String" in red color and not "Gleydson" in red

Answer

This is a pretty bad practice in general but:

String.class_eval do

  { red: 31, green: 32, yellow: 33, blue: 34, pink: 35, light_blue: 94, white: 97, light_grey: 37, black: 30 }.each do |color,value|
    define_method(color) do
      "\e[#{value}m #{self} \e[0m"
    end
  end

end

puts "Ruby".red
Comments