Skip to content

Instantly share code, notes, and snippets.

@camertron
Last active August 29, 2015 14:21
Show Gist options
  • Save camertron/107dc5d6b6de4f03cc70 to your computer and use it in GitHub Desktop.
Save camertron/107dc5d6b6de4f03cc70 to your computer and use it in GitHub Desktop.
Learning team bi-weekly code snippet for 5/13/2015

Three Useful Ruby Methods you Didn't Know Existed, and What to do With Them Now You've Wised Up

Yep, it's time for some cool Ruby trickery.

String#force_encoding

At their core, Ruby strings are just sequences of bytes. How you or your computer chooses interpret and display those bytes can mean the difference between legible text and complete garbage. Consider UTF-8 text for example. We now have great Unicode support in Ruby (as of 1.9) via the String#encode method and its friends, but again, strings are really just bytes.

Telling Ruby your string is encoded in UTF-8 tells it how to print your string on the screen or in your web app. For example, let's say you have a string that contains Japanese text (says 'arigato') "ありがと". Furthermore, let's pretend Ruby thinks the string is encoded in ASCII, which doesn't support Japanese characters. If you tried to print your string in the terminal, you might see something like this: "\xE3\x81\x82\xE3\x82\x8A\xE3\x81\x8C\xE3\x81\xA8". What you're seeing are the actual bytes of the string (represented as hexadecimal digits) because Ruby doesn't know how to print it correctly with ASCII encoding. Just call .force_encoding(Encoding::UTF_8) on the string to tell Ruby the correct encoding. The string should now appear correctly in the terminal.

Enumerable#each_cons

The #each_cons method loops over the elements of an array and yields consecutive sequences of elements. Since that probably made no sense to you (it didn't to me the first time), here's an example:

[1, 2, 3, 4, 5].each_cons(3) do |sequence|
  puts sequence.inspect
end

$> [1, 2, 3]
$> [2, 3, 4]
$> [3, 4, 5]

Array#sample

This handy method gets a random element from the array. You can specify how many random elements you want via an optional parameter:

arr = [5, 12, 7, 1, 3]
arr.sample  # => 12
arr.sample  # => 1

arr.sample(2)  => [1, 5]
arr.sample(3)  => [12, 3, 1]

Dir.glob

Globs are a Unix-ish pattern concept for matching on files and directories. Two stars (**) is a wildcard that matches on directories and a single star (*) is a wildcard that matches on files. You can combine these special characters with other path elements. Let's say I wanted to recursively match (i.e. look in infinitely deep directory structures) files in my Rails app directory. I'd use this glob: app/**/*.

Ruby provides the handy Dir.glob method that returns an array of paths that matched your glob pattern:

Dir.glob('app/**/*')  => ['app/controllers/home_controller.rb', 'app/models/user.rb', ...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment