Erik Trautman logo crest shield seal

Erik Trautman

Technical entrepreneurship, business strategy and product development

Ruby Explained: Blocks, Procs, and Lambdas, aka "Closures"

This post will explain blocks and Procs, with which you're probably at least somewhat familiar, but also some lesser known Ruby closures like Lambdas and Methods

One of the most confusing parts of learning basic Ruby (until your AHA! moment) is understanding what blocks are and how they work, mostly because it's something you probably haven't ever seen before trying out Ruby. It shouldn't be, because they're actually pretty simple. You HAVE already seen them before... they are commonly used as inputs to some of the iterators you've no doubt worked with like each or map.

Here, you'll learn more about blocks and also about their lessor known cousins, Procs, lambdas and Methods. By the end, you should be comfortable working with blocks and writing your own methods that take them. You should understand when you may need to use a Proc instead and the basics of the other two options -- lambdas and Methods.


Ruby Explained: Inheritance and Scope

This post will cover the basics of method and variable inheritance and scope in Ruby

You're able to break up your code into methods and classes but you'll also need to think more explicitly about which variables and methods are accessible where. I started talking about that concept a little bit in the previous post on classes, which dealt with the differences between class methods/variables versus instance methods/variables and the idea of inheriting the methods of a parent class. Here, you should take that general understanding and build on it further.

In a similar vein, you'll also learn more about how you can shield certain methods from being usable from outside of a class. You started learning about that idea when we used attr_accessor to make instance variables "visible" from outside your instance, but we'll dive deeper here and give you more tools to very explicitly decide what you do and don't want to show to the world.


Ruby Explained: Writing and Running Methods

This post will dive a bit deeper into how to write and run methods in Ruby the right way

You've been using methods since square one and writing your own as well so we'll focus on the essentials and the slightly more advanced stuff in this section, including how you actually run your code without needing to use IRB and some more stylistic issues that come up frequently.

What should you put into methods? Pretty much everything should be in a method, but each method should only do ONE thing. If it's doing two, it's time for another method. If it's doing a dozen, you probably need to start thinking about having a separate class.

Methods help organize your code by keeping you from repeating yourself. Anything that you find yourself doing repetetively should probably go in its own method.


Ruby Explained: Map, Select, and Other Enumerable Methods

This post will dive into map and select and all the other handy methods you get from Enumerable, Ruby's most useful module

You've learned about Array and Hash but only got half the story... they each have their own methods for adding and deleting and accessing data and they both implement their own version of the #each method to iterate over their items but what makes them really powerful in Ruby is the ability to use Enumerable methods as well as the basic ones you've just learned.

"Enumerable" is actually a "module", which means it is just a bunch of methods packaged together that can (and do) get "mixed in", or included, with other classes (like Array and Hash. That means that Ruby programmers don't have to write all those methods many different times - they just write them once, package them up as Enumerable, and tell Array and Hash to include them. As long as the class that wants to include Enumerable has its own #each method that Enumerable can use, it can get access to all the magic and joy of using the Enumerable methods by simply mixing it in.


Ruby Explained: Classes

This post will cover the basics of creating and working with classes in Ruby

When you start solving larger problems organization is key. You don't want 100 different methods and variables that do overlapping things. If you're trying to keep track of data (like a bunch of bad guys in a game you're building), you want to do so in the most organized way possible so you can recycle methods and only need to update that data in one place at a time.

Classes are here to make your life easier on that front and you'll learn about how to organize and use them here. In the process, you'll also need to understand which of their methods get inherited by who and the difference between instances of a class and the class itself.

You've written a lot of methods so far but they've generally been independent of each other. When you find that you want the same method to be run on a bunch of different objects without having to make a bunch of different if/else or case statements, you should start thinking about using a class.


Ruby Explained: Iteration

This post will get into Ruby loops and flow control

You can assemble code, tell the program which parts of it to execute, and wrap it all up in a method. There's still something missing... what if you want to make something happen a whole bunch of times? You certainly don't just run the method again and again manually. Luckily we've got several standard ways of iterating through a piece of code until we tell the program to stop.

You should understand the basic iterators for and while and understand how to use #each and #times. We'll talk more about blocks and the other Ruby iterators like #map and #select in the next posts, so it should be more obvious how #each and #times work after reading that.


Ruby Explained: Dates and Times

This post will cover the basics of working with dates and times in Ruby

When you're building a website, you'll inevitably come into contact with dates and times. When was that submitted? Show only posts created after this time. How long has that user been registered?

All languages have conventions for how they keep track of dates and times and, of course, Ruby is no different... just a bit easier than the rest. In general, computers keep track of time in terms of seconds since a specified point in time. Someone decided a long time ago that Time shall begin at midnight on January 1st, 1970, and so that's typically the "0th" second.

Ruby uses the Time class to let you work with dates and times, giving you some handy methods to find out about specific parts (like what day of the week it is) and to allow you to display them in a user-friendly fashion. You probably won't need to dive too deeply into this stuff until you start working with Rails but you do need to understand the basics (as laid out below).


Ruby Explained: Conditionals and Flow Control

This post will get into how Ruby chooses a path through your program, aka "flow control"

Now you've got an understanding of what tools you can use and it's time to start thinking about how the Ruby interpreter moves through your code. Sometimes you want to execute a certain chunk of code, other times you don't. In this post, you'll see the different ways of controlling the flow of your program.

You'll need to understand which types of things Ruby considers "true" and which ones it considers "false". "Truthiness" and "Falsiness" are ways of saying "what evaluates to true?"" and "what evaluates to false"? In many languages, there is some nuance to that question. In Ruby, it's simple: nil and false are false and that's it. Everything else is "truthy".


Ruby Explained: Other Random Tidbits

This post will get into a few other random things that are really useful but usually skipped by beginners

So What is nil? It represents nothing... literally. Before you assign a value to something, it starts as nil, for instance an item in an array or a variable:

> my_arr = []
=> []
> my_arr[3]
=> nil          # hasn't been assigned yet

Sometimes you want to know if a value or variable is nil before doing something (because otherwise the operation would throw a bunch of errors at you). Use the method nil? to ask whether it's nil or not beforehand.

> nil.nil?
=> true
> [].nil?
=> false        # Waitasecond....

Why is [] not nil? The array itself exists so it isn't nil... it just happens to contain no values yet so it's empty. If we asked for the first value of that array using [][0].nil?, that would be true


Ruby Explained: Hashes

This post will get into Hashes, which many Ruby newbies have never seen before but which are incredibly useful

Hashes may be a bit intimidating at first but they're actually pretty similar to arrays. They're basically just containers for data, like arrays, but instead of storing data based on numeric indices, you use "keys" which can be strings or symbols. This makes hashes more appropriate for storing data with a bit more depth to it.

A Hash is just a container for data where each piece of data is mapped to a Key. The data is called the Value. Keys can be either strings or symbols. Values can be anything, just like with arrays. A hash looks almost like an array, but with squiggly braces {} instead of hard ones [] There's no order to a hash (unlike an array)... you're accessing your data using strings anyway so it doesn't matter which order they're in.