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.
Set is a data structure that guarantees unique items.
Here is an example:
1 2 3 4 5 6 7 8 9 10 |
require 'set' unique_words = Set.new unique_words << 'abc' unique_words << 'ccc' unique_words << 'abc' p unique_words.entries # ["abc", "ccc"] |
The implementation of this data structure is based on the Hash
class, so there is no Array-like indexing.
But if you just need a bucket of data where all elements need to be unique all the time, then the Set
might be what you are looking for.
If you need to log some error / debug message Ruby has you covered with the Logger
class. This class provides everything you need to start logging.
In fact, this class is what Rails uses by default.
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:
1 2 3 4 5 6 |
require 'logger' logger = Logger.new(STDOUT) logger.info 'testing...' logger.warn 'fun with Ruby :)' |
This produces the following output:
1 2 |
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.
Maybe you don’t need to deal with prime numbers on a day-to-day basis, but it’s still good to know (specially 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
.
1 2 3 4 5 |
require 'prime' 5.prime? # true 11.prime? # true 20.prime? # false |
This class also includes a prime number generator.
Example:
1 2 |
Prime.take(10) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] |
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:
1 2 3 4 5 6 7 8 9 |
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
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:
1 2 3 |
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.
1 |
Dir.glob("*").count { |d| File.directory?(d) } |
Give this one a try the next time you need to do a file-system related task 🙂
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 🙂