Ruby Enumerable Methods and Active Record Comparison

Tyler J Funk
3 min readMar 11, 2020

--

Ruby’s built-in enumerable methods are a great way to iterate over each element inside a hash or array to manipulate the data in some way. Some quick examples include finding one entire element, finding all elements that meet a certain condition, or filtering out certain elements that don’t meet a certain condition, and much more. Active Record is a Ruby gem that adds a library of its own type of methods which accomplish similar tasks we use enumerable methods for, except they search through a database to retrieve those elements.

Below I will compare a few common built-in Ruby enumerable methods to those used in Active Record.

I will be using this data set to give examples of the Active Record methods:

find & find_by

Ruby’s find method returns the first element to meet the condition specified:

Active Record’s find_by method also returns the first object to meet the condition:

select / find_all & where

Ruby’s select and find_all methods are aliases of each other, and both return an array of every element that meets the condition specified:

Active Record’s where method also returns every object that meets a condition:

sort_by & order

Ruby’s sort_by method returns an array of all elements “sorted by” an attribute of each element (in this case, the length of a name):

Active Record’s order method also returns an array of all objects “ordered” by an attribute of each object (in this case, the ‘height’ of a ‘Pokemon’):

Conclusion

Although they are used in slightly different ways, it is clear to see the similarities between Ruby’s enumerable methods, and Active Record’s counterpart. This has been a brief demonstration of those similarities, but there are other methods that compare this closely as well.

Resources

--

--

Tyler J Funk
Tyler J Funk

Written by Tyler J Funk

Full Stack Web Developer && Creative Thinker && Flatiron School Grad && Continuous Learner

No responses yet