Gems – Ruby's building blocks
A gem is a ready-made Ruby package you can load into your program. The central collection is rubygems.org – almost 200,000 gems for everything imaginable.
On your own computer you install a gem in the terminal with gem install, then load it in IRB or your program with require:
$ gem install chunky_png
Successfully installed chunky_png-1.4.0
$ irb
irb(main):001:0> require "chunky_png"
=> trueIn real projects you list all gems in a file called Gemfile (one line per gem: gem "chunky_png") and fetch them in one go with bundle install – that's Bundler's job.
On this site, install_gem does that job for pure-Ruby gems, right in your browser (or use the 💎 panel on the left). Frequently used gems are cached locally (⚡) and install instantly:
install_gem "chunky_bacon"
require "chunky_bacon"
ChunkyBacon.shoutThat was chunky_bacon – this course's own gem, on rubygems.org. On your own computer, gem install chunky_bacon gives your programs this page's helpers – show_image, show_browser and friends – and chunkybacon run main.rb runs a program from the workshop just like here.
Now a gem that does real work: chunky_png – the name is no coincidence, dear foxes! 🥓 – creates PNG images in pure Ruby. Install it, load it with require – and show_image displays a picture right below the cell:
install_gem "chunky_png"
require "chunky_png"
image = ChunkyPNG::Image.new(8, 8, ChunkyPNG::Color::WHITE)
8.times { |i| image[i, i] = ChunkyPNG::Color.rgb(232, 114, 42) }
show_image imageEvery pixel is addressable: image[x, y] = color. You build colors with ChunkyPNG::Color.rgb(red, green, blue).
image (at least 8×8) and color the even rows bacon-red – ChunkyPNG::Color.rgb(193, 74, 46) – leaving the odd rows white. Show your work with show_image image.install_gem "chunky_png"
require "chunky_png"
# image = ChunkyPNG::Image.new(8, 8, ChunkyPNG::Color::WHITE)
# ...
# show_image image