How to output my ruby commandline text in different colours

后端 未结 10 1768
青春惊慌失措
青春惊慌失措 2021-01-30 03:15

How can I make the puts commands I output from a commandline based ruby program colour? I would appreciated any references to how I call each different colour also.

Lets

10条回答
  •  日久生厌
    2021-01-30 03:59

    Thought I'd add another solution as it does things a little differently and includes more colour codes:

    First some examples...

    Using method chaining:

    String.include(AnsiTextStyles)
    
    puts "How are you?".blue.bold + " " + 'I am good!'.red.bold
    puts '%s %s' % ["How are you?".blue.bold, 'I am good!'.red.bold]
    

    Using the style method and applying multiple attributes:

    puts "How are you?".style(:red)
    puts 'I am good!'.style(:blue, :underline)
    puts 'Good to hear'.style([:bg_magenta, :blink])
    

    This can be used to store style attributes in some manner to apply later:

    text_styles = {
        red_bold:       [:red, :bold],
        blue_underline: [:blue, :underline],
        pretty:         [:bg_magenta, :blink],
      }
    
    text_styles.each do |name, style|
      styled_text = "Text styled multiple ways".style(style)
      puts "%s: %s" % [name, styled_text]
    end
    

    I've given a few more examples on this gist I created and expanded the code to include refinements so that modifications to String are scoped.

    This is the basic code:

    module AnsiTextStyles
    
      TEXT_ATTRIBUTES = {
          # text properties
          none: 0, # turn off all attributes
          bold: 1, bright: 1, # these do the same thing really
          italic: 3, underline: 4, blink: 5,
          reverse: 7, # swap foreground and background colours
          hide: 8, # foreground color same as background
    
          # foreground colours
          black: 30, grey: 90, lt_grey: 37, :white => 97,
          red: 31, lt_red: 91, 
          green: 32, lt_green: 92,
          dk_yellow: 33, brown: 33, yellow: 93,
          blue: 34, lt_blue: 94,
          magenta: 35, pink: 95, lt_magenta: 95,
          cyan: 36, lt_cyan: 96,
          default: 39,
    
          # background colours
          bg_black: 40, bg_grey: 100, bg_lt_grey: 47, bg_white: 107,
          bg_red: 41, bg_lt_red: 101,
          bg_green: 42, bg_lt_green: 102,
          bg_dk_yellow: 43, bg_brown: 43, bg_yellow: 103,
          bg_blue: 44, bg_lt_blue: 104,
          bg_magenta: 45, bg_pink: 105, bg_lt_magenta: 105,
          bg_cyan: 46, bg_lt_cyan: 106,
        }
    
      def self.text_attributes
        TEXT_ATTRIBUTES.keys
      end
    
      # applies the text attributes to the current string
      def style(*text_attributes)
        codes = TEXT_ATTRIBUTES.values_at(*text_attributes.flatten).compact
        "\e[%sm%s\e[m" % [codes.join(';'), self.to_s]
      end
    
    end
    

提交回复
热议问题