SlidesLab: Simon Says
Next: Regexp >>

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"
comments powered by Disqus