Functional Ruby Idioms
Method Chaining
Method chaining passes each result into the next method call.
method chain
A method chain reads left to right when each step returns a value for the next step.
Method Chaining
method_chaining.rb
Replay: real traced execution (multi-file project)
raw_text = " ruby "
cleaned = raw_text.strip
normalized = cleaned.downcase
title = normalized.capitalize
label = title.then { |text| "Topic: #{text}" }
puts "raw=#{raw_text}"
puts "cleaned=#{cleaned}"
puts "label=#{label}"
raw_text = " trace "
cleaned = raw_text.strip
normalized = cleaned.downcase
title = normalized.capitalize
label = title.then { |text| "Topic: #{text}" }
puts "raw=#{raw_text}"
puts "cleaned=#{cleaned}"
puts "label=#{label}"
raw_text = " CODE "
cleaned = raw_text.strip
normalized = cleaned.downcase
title = normalized.capitalize
label = title.then { |text| "Topic: #{text}" }
puts "raw=#{raw_text}"
puts "cleaned=#{cleaned}"
puts "label=#{label}"
raw_text ← ruby , cleaned ← ruby, normalized ← ruby, title ← Ruby
1raw_text→ ruby = " ruby " #@raw_text=" trace ", " CODE "23cleaned→ ruby = raw_text.stripruby4normalized→ ruby = cleaned.downcaseruby5title→ Ruby = normalized.capitalizeRuby6label→ Topic: Ruby = titleRuby.then { |text| "Topic: #{text}" }78puts "raw=#{raw_text ruby }"9puts "cleaned=#{cleanedruby}"10puts "label=#{labelTopic: Ruby}"outputraw= ruby cleaned=ruby label=Topic: Ruby
raw_text ← trace , cleaned ← trace, normalized ← trace, title ← Trace
1raw_text→ trace = " trace "23cleaned→ trace = raw_text.striptrace4normalized→ trace = cleaned.downcasetrace5title→ Trace = normalized.capitalizeTrace6label→ Topic: Trace = titleTrace.then { |text| "Topic: #{text}" }78puts "raw=#{raw_text trace }"9puts "cleaned=#{cleanedtrace}"10puts "label=#{labelTopic: Trace}"outputraw= trace cleaned=trace label=Topic: Trace
raw_text ← CODE , cleaned ← CODE, normalized ← code, title ← Code
1raw_text→ CODE = " CODE "23cleaned→ CODE = raw_text.stripCODE4normalized→ code = cleaned.downcasecode5title→ Code = normalized.capitalizeCode6label→ Topic: Code = titleCode.then { |text| "Topic: #{text}" }78puts "raw=#{raw_text CODE }"9puts "cleaned=#{cleanedCODE}"10puts "label=#{labelTopic: Code}"outputraw= CODE cleaned=CODE label=Topic: Code