Object#dup

obj.dup -> obj
Returns: obj · Updated March 13, 2026 · Core Classes
objects copy duplication

dup creates a shallow copy of an object. It copies the object’s instance variables but not its singleton class (methods defined on that specific object).

Syntax

obj.dup

Parameters

dup accepts no parameters.

Examples

Basic usage

original = "hello"
copy = original.dup

original << " world"
puts original   # => "hello world"
puts copy       # => "hello"

With freeze

original = "immutable".freeze
copy_dup = original.dup

copy_dup << " modified"  # => "immutable modified"
# dup does NOT preserve freeze status
puts copy_dup.frozen?    # => false

Duplicating an array

original = [1, 2, [3, 4]]
copy = original.dup

original[2] << 5
puts original.inspect   # => [1, 2, [3, 4, 5]]
puts copy.inspect       # => [1, 2, [3, 4, 5]] - nested array is shared!

Duplicating to prevent mutation

def process_data(data)
  # Create a copy to avoid mutating the original
  working_copy = data.dup
  working_copy.map! { |x| x * 2 }
  working_copy
end

numbers = [1, 2, 3]
result = process_data(numbers)
puts result   # => [2, 4, 6]
puts numbers  # => [1, 2, 3] - original unchanged

Common Patterns

Defensive copying: Always dup input arguments if your method modifies them.

def sort_and_format(items)
  items = items.dup  # Don't mutate caller's array
  items.map(&:to_s).sort
end

Errors

  • TypeError — If the object is undupable (some special objects).

See Also