Chaining: A Ruby Idiom

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

Gotcha: each doesn't chain

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"

 Previous Lesson Next Lesson 

Outline

[menu]

/