Ruby colorize a section of text - ruby

I am writing a command line script in ruby and I am trying to color a section of lines. Currently, I am using the 'colorize' gem, but from the documentation it only lets you color one line of text at a time
puts "test".colorize(:green)
puts "test".colorize(:green)
puts "test".colorize(:green)
But, that seems a bit redundant to me and I would like to color all the lines of text, but only call 'colorize(:green)' once and not 3 times.
How can this be done in Ruby?

Define a method for this:
def putsg(text)
puts text.colorize(:green)
end
And than call that method:
putsg "test"
putsg "test"
putsg "test"

puts ["test", "test", "test"].join($/).colorize(:green)
or
puts ["test", "test", "test"].map{|s| s.colorize(:green)}

Regarding your statement "...but from the documentation it only lets you color one line of text at a time"
You can colorize different parts of the same line with different colors.
s = "Hello"
ss = "world"
puts "#{s.red} #{"there".white} #{s.blue}"
You can also accomplish your aim like this:
s = "test"
puts "#{s}\n#{s}\n#{s}".green
Or:
s1 = "check"
s2 = "this"
s3 = "out"
puts "#{s1}\n#{s2}\n#{s3}".green

You can also define a method like this:
The input is the color you want as a string and the text you want outputed. This will work in the command prompt.
def colorized_text(color,text)
#Find colors here: https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
color_code_hash = {
'red' => 196,
'green' => 40,
'yellow' => 226,
'blue' => 27,
}
puts"\e[38;5;#{color_code_hash[color]}m#{text}\e[0m"
end
I found this to be much better than using the colorize gem since that only gives you 8 colors. You can find all the colors on the ansi escape wiki page under the 8 bit section.

Related

How could I get a hex code when I give a color name

I'm making a telegram bot and I would like for it to be able to give a hex code against a color name. I know there are a heck of a lot of rgb colors but I also know there is a wikipedia article with known color names and hex codes, if I could be able to get the pages as a json it would help. Also, if the json says hex code = color name how can I invert that? How can I search by the value and not the name?
You could write your own Hash then Hash#invert it:
color_to_hex = { red: 'ff0000', green: '00ff00', blue: '0000ff' }
hex_to_color = color_to_hex.invert
color_to_hex[:red] #=> "ff0000"
hex_to_color['00ff00'] #=> :green
Or without creating the inverse hash:
colors_to_hex.key('00ff00') #=> :green
The other answers are fine. If you're looking for a gem that's already done the work for you, though, take a look at Color. Its Color::CSS[] method looks up a color by name and returns a Color::RGB object, which in turn has hex and html methods:
require "color"
aliceblue = Color::CSS["aliceblue"]
puts aliceblue.hex
# => f0f8ff
puts aliceblue.html
# => #f0f8ff
Color::RGB also has a by_hex static method, which will return a named Color::RGB object for the given hex code. The name method returns the name (if it has one):
require "color"
mystery_color = Color::RGB.by_hex("#ffefd5")
puts mystery_color.name
# => papayawhip
You can see it in action on repl.it: https://repl.it/#jrunning/EqualReasonableSpellchecker (If you get an error the first time you hit the run button, hit it again. repl.it sometimes has trouble with loading gems the first time.)
You can try following :
color_mappings = { 'yellow' => 'ffff00', 'red' => 'ff0000', 'green' => '00ff00', 'blue' => '0000ff' }
The hash can be inverted as follow :
inverted_color_mappings = color_mappings.invert
output :
{
"ffff00" => "yellow",
"ff0000" => "red",
"00ff00" => "green",
"0000ff" => "blue"
}
pattern = 'fff'
inverted_color_mappings.select{ |k,v| k[pattern] }
output :
{
"ffff00" => "yellow"
}

How do I search a text file for a string and then print/return/put out what line of the file it was found on as a number in Ruby

So, I want to use the number I get from it in this:
line = answer to question
database.read.lines[line]
Database being the text file I am searching in.
You can also do it this way :
text_to_find = 'some random text' # use gets method to take input from user
text_found_at_index = database.readlines.index{|line| not line[text].nil? }
Hope, this is what you require : )
I would try something like this:
query = gets.chomp
database.each_line.with_index do |line, index|
if line.include?(query)
puts "Line #{index}: #{line}"
end
end

how to make color for a string in Ruby

How to make color for a string in Ruby? For example, define a method make_color,
def make_color(str, :red)
end
Then the output will return the String str with red color.
I wonder whether there is a lib in ruby can help me do that?
ps: I prefer not using gem package.
Take a look at colorize gem
Install the gem and you can use colorize method to specify the color you want
require 'colorize'
puts "This is blue".colorize( :blue )
Or you can simply use the codes as you would in bash
for eg:
def make_color(str, color)
colors = {:red => 31, :green => 32, :blue => 34}
puts "\e[#{colors[color]}m #{str}\e[0m"
end

Split a complex file into a hash

I am running a command line program, called Primer 3. It takes an input file and returns data to standard output. I am trying to write a Ruby script which will accept that input, and put the entries into a hash.
The results returned are below. I would like to split the data on the '=' sign, so that the has would something like this:
{:SEQUENCE_ID => "example", :SEQUENCE_TEMPLATE => "GTAGTCAGTAGACNAT..etc", :SEQUENCE_TARGET => "37,21" etc }
I would also like to lower case the keys, ie:
{:sequence_id => "example", :sequence_template => "GTAGTCAGTAGACNAT..etc", :sequence_target => "37,21" etc }
This is my current script:
#!/usr/bin/ruby
puts 'Primer 3 hash'
primer3 = {}
while line = gets do
name, height = line.split(/\=/)
primer3[name] = height.to_i
end
puts primer3
It is returning this:
Primer 3 hash
{"SEQUENCE_ID"=>0, "SEQUENCE_TEMPLATE"=>0, "SEQUENCE_TARGET"=>37, "PRIMER_TASK"=>0, "PRIMER_PICK_LEFT_PRIMER"=>1, "PRIMER_PICK_INTERNAL_OLIGO"=>1, "PRIMER_PICK_RIGHT_PRIMER"=>1, "PRIMER_OPT_SIZE"=>18, "PRIMER_MIN_SIZE"=>15, "PRIMER_MAX_SIZE"=>21, "PRIMER_MAX_NS_ACCEPTED"=>1, "PRIMER_PRODUCT_SIZE_RANGE"=>75, "P3_FILE_FLAG"=>1, "SEQUENCE_INTERNAL_EXCLUDED_REGION"=>37, "PRIMER_EXPLAIN_FLAG"=>1, "PRIMER_THERMODYNAMIC_PARAMETERS_PATH"=>0, "PRIMER_LEFT_EXPLAIN"=>0, "PRIMER_RIGHT_EXPLAIN"=>0, "PRIMER_INTERNAL_EXPLAIN"=>0, "PRIMER_PAIR_EXPLAIN"=>0, "PRIMER_LEFT_NUM_RETURNED"=>0, "PRIMER_RIGHT_NUM_RETURNED"=>0, "PRIMER_INTERNAL_NUM_RETURNED"=>0, "PRIMER_PAIR_NUM_RETURNED"=>0, ""=>0}
Data source
SEQUENCE_ID=example
SEQUENCE_TEMPLATE=GTAGTCAGTAGACNATGACNACTGACGATGCAGACNACACACACACACACAGCACACAGGTATTAGTGGGCCATTCGATCCCGACCCAAATCGATAGCTACGATGACG
SEQUENCE_TARGET=37,21
PRIMER_TASK=pick_detection_primers
PRIMER_PICK_LEFT_PRIMER=1
PRIMER_PICK_INTERNAL_OLIGO=1
PRIMER_PICK_RIGHT_PRIMER=1
PRIMER_OPT_SIZE=18
PRIMER_MIN_SIZE=15
PRIMER_MAX_SIZE=21
PRIMER_MAX_NS_ACCEPTED=1
PRIMER_PRODUCT_SIZE_RANGE=75-100
P3_FILE_FLAG=1
SEQUENCE_INTERNAL_EXCLUDED_REGION=37,21
PRIMER_EXPLAIN_FLAG=1
PRIMER_THERMODYNAMIC_PARAMETERS_PATH=/usr/local/Cellar/primer3/2.3.4/bin/primer3_config/
PRIMER_LEFT_EXPLAIN=considered 65, too many Ns 17, low tm 48, ok 0
PRIMER_RIGHT_EXPLAIN=considered 228, low tm 159, high tm 12, high hairpin stability 22, ok 35
PRIMER_INTERNAL_EXPLAIN=considered 0, ok 0
PRIMER_PAIR_EXPLAIN=considered 0, ok 0
PRIMER_LEFT_NUM_RETURNED=0
PRIMER_RIGHT_NUM_RETURNED=0
PRIMER_INTERNAL_NUM_RETURNED=0
PRIMER_PAIR_NUM_RETURNED=0
=
$ primer3_core < example2 | ruby /Users/sean/Dropbox/bin/rb/read_primer3.rb
#!/usr/bin/ruby
puts 'Primer 3 hash'
primer3 = {}
while line = gets do
key, value = line.split(/=/, 2)
primer3[key.downcase.to_sym] = value.chomp
end
puts primer3
For fun, here are a couple of purely-functional solutions. Both assume that you've already pulled your data from the file, e.g.
my_data = ARGF.read # read the file passed on the command line
This one feels sort of gross, but it is a (long) one-liner :)
hash = Hash[ my_data.lines.map{ |line|
line.chomp.split('=',2).map.with_index{ |s,i| i==0 ? s.downcase.to_sym : s }
} ]
This one is two lines, but feels cleaner than using with_index:
keys,values = my_data.lines.map{ |line| line.chomp.split('=',2) }.transpose
hash = Hash[ keys.map(&:downcase).map(&:to_sym).zip(values) ]
Both of these are likely less efficient and certainly more memory-intense than your already-accepted answer; iterating the lines and slowly mutating your hash is the best way to go. These non-mutating variations are just a mental exercise.
Your final answer should use ARGF to allow filenames on the command line or via STDIN. I would write it like so:
#!/usr/bin/ruby
module Primer3
def self.parse( file )
{}.tap do |primer3|
# Process one line at a time, without reading it all into memory first
file.each_line do |line|
key, value = line.chomp.split('=', 2)
primer3[key.downcase.to_sym] = value
end
end
end
end
Primer3.parse( ARGF ) if __FILE__==$0
This way you can either call the file from the command line, with or without STDIN, or you can require this file and use the module function it defines in other code.
OK I have it (almost). The only problem is it is adding a \n at the end of each value.
puts 'Primer 3 hash'
primer3 = {}
while line = gets do
key, value = line.split(/\=/)
puts key
puts value
primer3[key.downcase] = value
end
puts primer3
{"sequence_id"=>"example\n", "sequence_template"=>"GTAGTCAGTAGACNATGACNACTGACGATGCAGACNACACACACACACACAGCACACAGGTATTAGTGGGCCATTCGATCCCGACCCAAATCGATAGCTACGATGACG\n", "sequence_target"=>"37,21\n", "primer_task"=>"pick_detection_primers\n", "primer_pick_left_primer"=>"1\n", "primer_pick_internal_oligo"=>"1\n", "primer_pick_right_primer"=>"1\n", "primer_opt_size"=>"18\n", "primer_min_size"=>"15\n", "primer_max_size"=>"21\n", "primer_max_ns_accepted"=>"1\n", "primer_product_size_range"=>"75-100\n", "p3_file_flag"=>"1\n", "sequence_internal_excluded_region"=>"37,21\n", "primer_explain_flag"=>"1\n", "primer_thermodynamic_parameters_path"=>"/usr/local/Cellar/primer3/2.3.4/bin/primer3_config/\n", "primer_left_explain"=>"considered 65, too many Ns 17, low tm 48, ok 0\n", "primer_right_explain"=>"considered 228, low tm 159, high tm 12, high hairpin stability 22, ok 35\n", "primer_internal_explain"=>"considered 0, ok 0\n", "primer_pair_explain"=>"considered 0, ok 0\n", "primer_left_num_returned"=>"0\n", "primer_right_num_returned"=>"0\n", "primer_internal_num_returned"=>"0\n", "primer_pair_num_returned"=>"0\n", ""=>"\n"}

How can I display the output of an array in Ruby Shoes?

I've got this as my code
openAll = File.open('N:\Josh\Blondie\db.txt')
allNumbers = Array.new
allNumbers=[]
openAll.each_line {|line|
allNumbers.push line
}
puts allNumbers
and I'd like to be able to display the output of this code in a new window with Ruby Shoes, I can't seem to get it to display anything though. The contents of the file are names and phone numbers.
Any ideas?
Here's an example of outputting text to a shoes window. Using a puts statement just outputs to the shell, not to the Shoes app.
Shoes.app :title => "GUI RAW file converter, for the CLI challenged",
:resizable => true do
background white
stack do
flow {
background gray, :height => 30
caption "Caption", :margin => 8, :stroke => white
stack {
para 'This is a fancy line I just printed to the window'
####### Here's an example line you could use to put out the array...
allNumbers.each do |number|
para "#{number}"
end
}
}
end
end
I guess you should use the method Kernel#alert instead of Kernel#puts.
http://shoesrb.com/manual/Built-in.html

Resources