This site is a preview of the curriculum for our Summer 2018 bootcamp in Burlington, Vermont. As we continue our preparation, courses and lessons will appear and disappear; we will rename, rearrange, clarify, and obfuscate as needed... Please consider this a work in progress and keep checking in.

Ruby Basics:
Chaining


Slides

Chaining: A Ruby Idiom

s.split.map{|w|w.capitalize}.join(' ')
  • this technique is called method chaining
  • each operation changes the result of the previous operation
  • in this case, it
    • splits a string into words
    • capitalizes each word
    • joins the words back together

Gotcha: each doesn't chain

  • each returns the original collection
  • map returns a new collection

Solution A: use map and chaining

s.split.map{|w|w.capitalize}.join(' ')

Solution B: use each and !

s.split.each{|w|w.capitalize!}.join(' ')

Solution C: use each and an accumulator

capitalized = []
s.split.each{|w|
  capitalized << w.capitalize
}
capitalized.join(' ')

delving into map

s                   # "foo_bar"
  .split("_")       # ["foo", "bar"]
  .map {|w|         # "foo", then "bar"
    w.capitalize    # "Foo", then "Bar"
  }                 # ["Foo", "Bar"]
  .join(" ")        # "Foo Bar"

Labs



Comments

comments powered by Disqus