RubyGuides
Share this post!

5 Useful Examples From The Ruby Standard Library

The Ruby Standard Library is a series of modules & classes that come with Ruby but are not part of the language itself.

These classes offer a variety of utilities like:

  • Base64 encoding
  • Prime number generation
  • DNS resolution

In this article I’m going to show you 5 of these classes with useful examples.

Ruby Logger Class

If you need to log some error or debug message Ruby has you covered with the Logger class.

This class provides everything you need to start logging!

To use the Logger class you can simply create a Logger object & give it an output stream (or a file name) as a parameter. Then you can use the different logging levels to register your message.

The logging levels are:

  • debug
  • info
  • warn
  • error
  • fatal

Example:

require 'logger'

logger = Logger.new(STDOUT)

logger.info 'testing...'
logger.warn 'fun with Ruby :)'

This produces the following output:

I, [2016-05-14T15:50:21.367590 #12148]  INFO -- : testing...
W, [2016-05-14T15:50:21.846651 #12148]  WARN -- : fun with Ruby 🙂

The first character is an abbreviated form of the logging level (I for Info, W for Warn)… Then you have a timestamp, and the current process id (which you can get in Ruby using Process.pid).

Finally, you have the full logging level & the actual message.

You can change this format by providing a new formatter.

Working with Prime Numbers

Maybe you don’t need to deal with prime numbers on a day-to-day basis, but it’s still good to know (especially if you like programming challenges) that Ruby has good support for them via the Prime class.

When you require Prime it will add the prime? method to Fixnum.

Example:

require 'prime'

5.prime?  # true
11.prime? # true
20.prime? # false

This class also includes a prime number generator.

Example:

Prime.take(10)
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

How to Use The StringIO Class

The StringIO class allows you to create a string that behaves like an IO object.

This means that you can work with this string like if you were reading from a file or STDIN (Standard Input).

Here is an example:

require 'stringio'

io = StringIO.new

io << 'test'
io << 'code'

puts io.string
# "testcode"

Notice a few things:

When you add data into your StringIO object it will not add spaces or newlines for you, and to get the actual string you need to call the string method.

Also you can't use array indexing to access individual characters, like you can with a regular string.

When is this useful?

Well, sometimes you may want to substitute a file or some other IO object for another object that you have more control over. For example, in a testing environment you can replace STDOUT with a StringIO object.

You can see a real world example from Rails here: https://github.com/rails/rails/blob/52ce6ece8c8f74064bb64e0a0b1ddd83092718e1/activesupport/test/logger_test.rb

Encoding & Decoding Base64

Base64 is an encoding format that's common on the internet.

It looks like this:

"cnVieQ=="

Why is it useful?

URLs have a restricted set of characters allowed, sometimes you want to include those & Base64 makes this possible.

Here's how to encode:

require 'base64'

Base64.encode64("ruby")
"cnVieQ=="

Here's how to decode:

require 'base64'

Base64.decode64("cnVieQ==")
"ruby"

Working With Paths

The Pathname class wraps several file-system exploring utilities, like Dir & File, in a much more powerful class.

While the method names are the same, they return Pathname objects instead of strings or arrays. And what this means is that you can keep working with the results with all the file-related methods.

This is a great example:

require 'pathname'

Pathname.glob("*").count(&:directory?)

If you tried to do this with Dir, you would have to use this code, which is not as elegant.

Dir.glob("*").count { |d| File.directory?(d) }

Give this one a try the next time you need to do a file-system related task 🙂

Conclusion

I hope you found these examples useful! Make sure to explore the Standard Library a bit more so you can learn what it can do for you.

Don't forget to share this post if you liked it 🙂