Ruby Enumerable Tips

After 2 weeks at FlatIron here is a recap of some things I learned in Ruby.

During your time at Bootcamp you will quickly discover the need for two very useful and powerful Enumerables: .select and .map

.select aka .filter aka .find_all

I use this when trying to access instance information stored in anotherClass. i.e. when trying to find items in a has many/belongs to relationship.

(elements).select { |single element| conditional block }

returns #=> a new_array of all elements where conditional block is true

.map aka .collect

I find myself using this in conjunction with .select when trying to get a new array of information stored in anotherClass. i.e. when trying to find items in a has many through relationship.

(elements).map { |single element| operating block }

returns #=> a new_array of all elements where element is changed per operating block

A bonus enumerable!

each_with_object aka .select and .map in one (for this example)

A good friend of mine in my cohort discovered this enumerable and shared it with me. Its the go to for all my has many of many and has many through labs

Standard definition states. .each_with_object — Iterates the given block for each element with an arbitrary object given, and returns the initially given object. For me that means I can iterate over each instance of a Class, shovel the element property i want into an array, only for the the argument I stated.

I hope these examples will help you on your journey through Ruby.

source: https://ruby-doc.org/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store