An Intro to Elegant Ruby

An Intro to Elegant Ruby

When I first started coding I heard from a lot of different sources, “First make it work, then make it pretty.” As I continue to learn (and continue to struggle with the making it work part) I began to wonder what that pretty code might look like.

A really common expression in Ruby is an if/else statement. If you’ve been coding for any length of time you’ve probably seen an if/else statement and even written a couple yourself. But have you used a ternary expression? If not, maybe you’ve seen one on Stackoverflow or in a Youtube video and thought, “what’s that?” Take a look at the example below and see if you can figure it out, now that you know that it’s related to an if/else statement.

weather == 'raining' ? bring_an_umbrella : enjoy_the_sun

So the basic formatting is :

condition ? true : false

The way the ternary operator works is that what ever comes first, before the ‘?’ is a conditional statement (the thing being validated on a true or false basis). After the ‘?’ we decide what we want to happen if the condition is true. If the condition is true whatever we put here will be run, if it’s false whatever we put after the ‘:’ will run. This isn’t going to make your code ‘SuPeR Elit3’ but it can make it more compact, saving you a few lines here or there and it looks pretty cool.

Another thing you probably do a lot is create arrays with numbers and/or letters. It can be pretty boring to write every single number in an array. If you’re lazy like me, and you should be, there’s a much faster way to accomplish the same goal using splats.

[*1..10]
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# You can even do multiple splats at once
[*1..5, *'a'..'e']
#=> [1, 2, 3, 4, 5, "a", "b", "c", "d", "e"]
# If you're doing an array of letters you can also use 'character literals'
# For example ?a == 'a' 
so...
[*?a..?e]
#=> ["a", "b", "c", "d", "e"]

Splats can be used for more than just creating arrays with single digit or alpha characters. Do a little digging and even better, some experimenting and you may find uses for them that make your life a little easier.

What if your arrays don’t contain single digits? What if they’re a little more complex? Say no more fam, I got you.

["You're" "probably" "doing" "a" "lot" "of" "this" "huh"]

Well that’s fine, it does work, BUT what if I told you there was a better way and you could give that pinky finger of yours a rest? I told you, I got you.

%w[So instead you should definitely try this]

# Did you know that what I wrote above returns what I wrote below?
 
#=>["So", "instead", "you", "should", "definitely", "try", "this"]
# Open up an irb and try it yourself

I know what you’re thinking, you’re welcome, your fingers are welcome, but I’m not even finished yet. One last trick to save you time and energy; two things you’ll need plenty of on your road to becoming a Software Engineer. Let’s say you have three classes: an artist, a genre, and songs. Songs belong to both an artist and a genre, and the artist class has a many to many relationship with the genre class through songs. You may have some methods like the ones below in your Artist class.

def songs
    Songs.all.select { |song| song.artist == self }
end

def genres
        songs.map { |song| song.genre}
end

Well, it works, but we’re trying to transcend the first part of, “First make it work, then make it pretty.” So what can we do to make this pretty and better yet, save you time, you might find yourself writing these .select and .map methods quite frequently.

def songs
    Songs.all.select { |song| song.artist == self }
end

def genres
    songs.map(&:genre)
end

What I’m doing in the genres method is using a unary ampersand (&:), which basically calls to_proc on the object, well kind of. Procs and blocks go much deeper and maybe I’ll write a post about them one day. For now, what I’m doing in the example above is calling to_proc on an array of songs belonging to an artist. Calling Array#map is probably the most common use for this. It works by calling to_proc on the :genre symbol. This converts the symbol to a proc, then a block, which in this case will return the genres of the songs belonging to a specific artist.

To view or add a comment, sign in

More articles by Christopher Lempke

  • CSS Flexbox Explained — Justify Content

    One of the most frustrating things for me when I started building web apps in Javascript and even Ruby on Rails was…

    2 Comments
  • Music for Coding

    I get distracted very easily. Sometimes while I’m coding, precious focus drifts away from the problem I’m trying to…

Others also viewed

Explore content categories