Kernel#yield_self

obj.yield_self { |obj| block } -> object
Returns: Object · Updated March 13, 2026 · Kernel Methods
blocks chaining functional pipelines

The yield_self method (introduced in Ruby 2.5) passes the receiver to a block and returns the result. It’s useful for chaining operations on any object without changing the original.

Basic Usage

# Simple chaining
result = 5.yield_self { |x| x * 2 }  # => 10
"hello".yield_self { |s| s.upcase }  # => "HELLO"

Practical Examples

String Pipelines

# Clean up and transform string
filename = "  MY_FILE.TXT  "

filename
  .yield_self { |s| s.strip }
  .yield_self { |s| s.downcase }
  .yield_self { |s| s.gsub(" ", "_") }
# => "my_file.txt"

Number Transformations

# Chain numeric operations
100
  .yield_self { |n| n * 0.1 }
  .yield_self { |n| n.round(2) }
  .yield_self { |n| "$#{n}" }
# => "$10.0"

Safe Method Calling

# Similar to Object#then (Ruby 2.5+)
obj.yield_self { |o| o.method_that_might_fail }

Data Processing

# Parse and transform
data = "100"

data
  .yield_self { |s| Integer(s) }
  .yield_self { |n| n * 2 }
  .yield_self { |n| { result: n } }
# => {:result=>200}

Comparison with other approaches

# Using yield_self
result = object.yield_self { |o| o.transform }

# Using tap (modifies self, returns self)
result = object.tap { |o| o.transform! }

# Using then (Ruby 2.5+ alias)
result = object.then { |o| o.transform }

# Traditional
result = transform(object)

With Chained Methods

# Combine with regular methods
(1..10)
  .yield_self { |r| r.to_a }
  .select { |n| n.even? }
  .sum
# => 30

Why Use yield_self

  • Method chaining on non-enumerable objects
  • Creating pipelines
  • Cleaner transformation code
  • Alternative to temporary variables
  • Works with any object type

See Also