Method chaining lets you call many methods one after another in a single line. It makes code shorter and easier to read.
Method chaining patterns in Ruby
class Example def initialize(value) @value = value end def add(number) @value += number self end def multiply(number) @value *= number self end def result @value end end obj = Example.new(5) obj.add(3).multiply(2).result # => 16
Each method returns self to allow chaining.
The last method can return a value instead of self to get the final result.
upcase and reverse changes the string step-by-step.class ChainExample def initialize(text) @text = text end def upcase @text = @text.upcase self end def reverse @text = @text.reverse self end def show @text end end obj = ChainExample.new("hello") puts obj.upcase.reverse.show
class ChainExample def initialize(text) @text = text end def clear @text = "" self end def add_text(new_text) @text += new_text self end def show @text end end obj = ChainExample.new("") puts obj.add_text("Hi").add_text("!").show
class ChainExample def initialize(text) @text = text end def upcase @text = @text.upcase self end def clear @text = "" self end def show @text end end obj = ChainExample.new("hello") puts obj.clear.upcase.show
This program creates a calculator object starting at 10. It then adds 5, subtracts 3, multiplies by 4, and divides by 2 using method chaining. Finally, it prints the result.
class Calculator def initialize(value) @value = value end def add(number) @value += number self end def subtract(number) @value -= number self end def multiply(number) @value *= number self end def divide(number) if number == 0 puts "Cannot divide by zero" self else @value /= number.to_f self end end def result @value end end calculator = Calculator.new(10) puts "Initial value: #{calculator.result}" calculator.add(5).subtract(3).multiply(4).divide(2) puts "After chaining operations: #{calculator.result}"
Time complexity depends on each method's work; chaining itself adds no extra cost.
Space complexity is usually constant since methods modify the same object.
Common mistake: forgetting to return self in methods breaks the chain.
Use method chaining when you want smooth, readable sequences of operations on the same object.
Method chaining calls multiple methods on the same object in one line.
Each method (except the last) returns self to continue the chain.
It makes code shorter and easier to read by avoiding repeated object names.