Sitemap

Ruby Enumerable

2 min readDec 6, 2022

--

Moving from Front End programming to Back End programming was challenging. What I enjoyed most about Javascript and React is the ability to test our code in our browser console as well as seeing our page render based on changes in state. With ruby programming, the methods are tested with ruby tools like rake console and binding.pry

What I found very useful in Ruby programming is the enumerable modules

What are Ruby Enumerable?

Enumerable allows the sorting, searching and traversal through our collection of data.

Some familiar enumarable that we used in Javascript are .filter, .each, .map.

Is there a difference between an enumerator and an enumerable?

An enumerator allows you to instantiate an instance in our code using an enumerable without a block of code.

[1, 2, 3].each

The great thing about Ruby is that there are many enumerable to help evaluate our data. Here are a few enumerable I found easiser to understand that could be useful.

Minmax_by

Evaluates our data and returns the min and max values in our code

superheroes = (superman, batman, aquaman, wonderwoman)
superheroes.minmax_by { |x| x.length } #=> ["batman", "wonderwoman"]

.reject

Get Matthew Lui’s stories in your inbox

Join Medium for free to get updates from this writer.

Returns a collection of elements in our array that has a condition of false

[1, 2, 3, 4, 5].reject { |num| num.even? } #=> [1, 3, 5]

.drop

Drops the first element we evaluate and returns the rest of the elements in our array.

num = [1, 2, 3, 4, 5, 0]
num.drop(3)#=> [4, 5, 0]

Take_while

Our code stops iterating once it returns nil or false

a = [1, 2, 3, 4, 5, 0]
a.take_while { |i| i < 3 } #=> [1, 2]

Here the links that I referenced for my blog.

Ruby-Docs.org

Docs.ruby-lang.org

Api.rubyonrails.org

--

--

Matthew Lui
Matthew Lui

Written by Matthew Lui

Full Stack Software Engineer Student