Ruby Enumerable Tips

SunJet Liu
2 min readSep 28, 2020

--

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

(1..10).find_all { |i|  i % 3 == 0 }   #=> [3, 6, 9][1,2,3,4,5].select { |num|  num.even?  }   #=> [2, 4]MovieChar.all.select {|mc| mc.character == self} #=> list of instances where .character of MovieChar is equal to current instance

.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 = [ "a", "b", "c", "d" ]
a.collect { |x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
a.map.with_index { |x, i| x * i } #=> ["", "b", "cc", "ddd"]
a #=> ["a", "b", "c", "d"]
mc=MovieChar.all.select {|mc| mc.character == self}
mc.map{|mcinst| mcinst.movie } #=> Sets array var to list of instances where .character of MovieChar is equal to current instance. Then use .map over the array to get only the movies that the character appears in.

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.

evens = (1..10).each_with_object([]) { |i, a| a << i*2 }#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]MovieCharacter.all.each_with_object([]) {|mc, arr| arr << mc.movie if mc.character == self} #=> is equivalent to {
mc=MovieChar.all.select {|mc| mc.character == self}
mc.map{|mcinst| mcinst.movie } #
}

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

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

--

--

No responses yet