Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sparklines in Ruby
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# prints a sparkline in the terminal using the supplied list of numbers
# examples:
# spark.rb 10 20 30 100 90 80
# spark.rb 1 2 0.4 0.1 1.3 0.7
@ticks = %w[▁ ▂ ▃ ▄ ▅ ▆ ▇]
values = ARGV.map { |x| x.to_f }
min, range, scale = values.min, values.max - values.min, @ticks.length - 1
puts values.map { |x| @ticks[(((x - min) / range) * scale).round] }.join
@judofyr

This comment has been minimized.

Copy link

commented Nov 15, 2011

This gives smoother ticks:

@ticks = %w[▁ ▂ ▃ ▄ ▅ ▆ ▇]
@jcromartie

This comment has been minimized.

Copy link
Owner Author

commented Nov 15, 2011

Indeed. Thanks!

@ghost

This comment has been minimized.

Copy link

commented Nov 15, 2011

Small problem if range = 0...

@jcromartie

This comment has been minimized.

Copy link
Owner Author

commented Nov 15, 2011

You're right @newfoundresearch. However, a sparkline for a dataset with a range of 0 wouldn't be very interesting anyway, would it? :)

@GarrisonJ

This comment has been minimized.

Copy link

commented Jan 3, 2013

@ticks = %w[▁ ▂ ▃ ▄ ▅ ▆ ▇]
values = ARGV.map { |x| x.to_f }
min, range, scale = values.min, values.max - values.min, @ticks.length - 1
if !(range == 0)
  puts values.map { |x| @ticks[(((x - min) / range) * scale).round] }.join
else
  puts values.map { |x| @ticks[1] }.join
end

Just in case range == 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.