Ruby Basics:



Chaining: A Ruby Idiom{|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{|w|w.capitalize}.join(' ')

Solution B: use each and !

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

Solution C: use each and an accumulator

capitalized = []
  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"