Ruby Method Chaining

Linking together multiple Ruby Enumerable Methods in order to maintain concise, readable code

Daisy Chain Flower Crown
Daisy chain (Bellis perennis) CREDIT: RICHARD BLOOM/GETTY IMAGES

Basic Concept

new_array = [18, 22, 33, 3, 5, 6]new_array.select {|number| number > 10 } => [18, 22, 33]
new_array.select {|number| number > 10 }.sum 
=> 73

Multiple Links In The Chain

string = "the quick brown fox jumps over the lazy dog"
1) string.split 
=> ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
2) string.split.map{|word| word.capitalize}
=> ["The", "Quick", "Brown", "Fox", "Jumps", "Over", "The", "Lazy", "Dog"]
3) string.split.map{|word| word.capitalize}.join(" ")
=> "The Quick Brown Fox Jumps Over The Lazy Dog"

Databases And Many-to-Many Relationships

#in the Scientist Model: def mission_method   Mission.all.select{|mission| mission.scientist_id == self.id}end#in the console: @scientist.mission_method => 
[#<Mission:0x00007f989e2dff08
id: 6,
name: "Sleeper",
scientist_id: 5,
planet_id: 6,
created_at: Tue, 23 Mar 2021 20:27:57 UTC +00:00,
updated_at: Tue, 23 Mar 2021 20:27:57 UTC +00:00>,
#<Mission:0x00007f989e2df530
id: 12,
name: "As You Were",
scientist_id: 5,
planet_id: 19,
created_at: Tue, 23 Mar 2021 20:27:57 UTC +00:00,
updated_at: Tue, 23 Mar 2021 20:27:57 UTC +00:00>]
#in the Scientist Model:def mission_methodMission.all.select{|mission| mission.scientist_id == self.id}.map{|mission| mission.planet.name}end#in the console:@scientist.mission_method => ["Deep Space Nine", "Beta Quadrant"]
Photo by Ju Guan on Unsplash

Spacing

#all code in one continuous line:Mission.all.select{|mission| mission.scientist_id == self.id}.map{|mission| mission.planet.name}.first#same code with each new method entered on its own line:Mission.all.select{|mission| mission.scientist_id == self.id}.map{|mission| mission.planet.name}.first

Closing Thoughts

Photo by James Harrison on Unsplash

--

--

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
Amanda Nikrant

Full stack software engineer with a background in quality control, and an eye for details and logic. Passionate about learning and inclusive environments.