Ruby Inside
Published in

Ruby Inside

A Weird and Wonderful Trip through Ruby’s Standard Library

Shellwords

First up: the Shellwords module. It provides a few nice methods which make it easier to build and parse shell commands from within Ruby.

$> filename = "Alex's Notes.txt"
$> `cat #{filename}`
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
=> ""
$> `cat #{filename.shellescape}`
=> "Apostrophes in a filename? 🤔"

English: for when you want less $$

Pop quiz: what does $$ return?

$> `exit 42`
=> ""
$> $CHILD_STATUS # or $? for the purists
=> #<Process::Status: pid 25566 exit 42>

Prime

If you require the Prime module, Ruby can tell you if a number is prime:

$> 5.prime?
=> true
$> Prime::EratosthenesGenerator.new.take(10)
=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
$> Prime.take(10) # uses Eratosthenes under the hood, by default
=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Abbrev

This is probably the weirdest and most wonderful module I found in my spelunking. According to the docs, Abbrev:

$> require 'abbrev'
=> true
$> %w(ruby rules).abbrev
=> {
"ruby"=>"ruby",
"rub"=>"ruby",
"rules"=>"rules",
"rule"=>"rules",
"rul"=>"rules"
}
$> names = %w(Alex Amy Ayla Amanda)
$> names.abbrev.keys.select { |n| n.length > 2 }
=> ["Alex", "Ale", "Amy", "Ayla", "Ayl", "Amanda", "Amand", "Aman", "Ama"]

Last, but not least…

Chances are you’ve made an HTTP request from your Ruby program at some point. You probably used Net::HTTP (or maybe another gem that uses it under the hood).

$> inbox = Net::POP3.new('pop.gmail.com')
=> #<Net::POP3 pop.gmail.com: open=false>
$> inbox.start('your-email-here@gmail.com', 'supersecret')
=> #<Net::POP3 pop.gmail.com: open=true>
$> inbox.each_mail { |m| puts m.pop.split("\n").grep(/Subject/) }
Subject: Hello IRB!
$> pop.finish
=> "+OK Farewell."

Conclusion

What a ride! I hope I’ve opened your mind to some new possibilities with the language you know and love. I certainly learned a ton, and digging into these weird, dusty corners of Ruby just makes me love it even more. ❤️

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Taylor

Alex Taylor is a Senior Software Developer at Clio. He has a passion for Ruby, loves tea, and rides his bike (almost) everywhere.