4

There are plenty of coloring libraries: colored, term-ansicolor. But is there any which can do this:

puts "#{'hello'.red} world!".bold 

And world! should be bold.

To make it clear, I want to get this:

"\e[1m\e[31mhello\e[0m\e[1m world!\e[0m" 

or better even this (just shorter):

"\e[1;31mhello\e[0;1m world!\e[0m" 

instead of this:

"\e[1m\e[31mhello\e[0m world!\e[0m" 
4
  • 2
    The API you are proposing doesn't make sense. How would the library know when to reset the colors/styles? Commented Jan 18, 2011 at 18:24
  • @cam: It surely makes sense. What do you expect from html <strong><span style="color:red">hello</span> world!</strong>? I want same thing in bash and I was just trying to know if there is already such library and if not I'll write my own. Commented Jan 18, 2011 at 20:05
  • your HTML example is not equivalent. What is the expected output of "red #{"green".green} red".red? Commented Jan 18, 2011 at 21:32
  • @cam: Why not equivalent?? I want all string to be bold and hello to be red (and bold as it is part of string). For your example html equivalent is <span style="color:red">red <span style="color:green">green</span> red</span>. Commented Jan 19, 2011 at 2:25

3 Answers 3

8

As there is none, I wrote my own, with blackjack and hookers smart one — smart_colored

gem install smart_colored 

and run

require 'smart_colored/extend' # without extend you'll need to use 'string'.colored.red puts "#{'hello'.red} world!".bold 
Sign up to request clarification or add additional context in comments.

Comments

0

The lib is called Highline It has a color method: say("This should be <%= color('bold', BOLD) %>!") Which can be easily used to implement String#bold.

2 Comments

@tig, read the answer one more time. What you asked for is a String#bold method. Daniel provided a way for you to make one. This would work for String#red, etc, too.
@Mark: I told in my question that I don't need simple coloring library (with such problem google would help me with pleasure) as they all do same error — they don't understand nesting. Adapting Daniel's code gave me same result as colored (HighLine.new.color("#{HighLine.new.color('hello', HighLine::RED)} world!", HighLine::BOLD)): ` world!` is not bold
0

In case you are using highline I made a gem that extends colors and provides helpers such as:

say_bold 'this is bold text' 

https://github.com/bonzofenix/highline-color

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.