← Back to Ruby Operators

Dash Symbol

The dash symbol (-) can be used as both a unary and binary operator. It is also used in negative numbers and defining floats. You'll also see it show up in proc syntax (-> { ... }).

Subtraction / Minus Operator

Subtract two numbers.

> 5 - 4
=> 1

We can also subtract in other contexts, like how Array#- defines its own version of subtraction.

> [1,3,4] - [4]
=> [1, 3]

Numeric Literals

We can define negative numbers (with a leading dash) as well as floats using the e-N notation.

> -10
=> -10
> 1234e-2
=> 12.34

Dash as a Unary Operator

The unary minus operator can be used to negate a number.

def move_north(steps)
  move_along_x_axis(steps)
end

def move_south(steps)
  move_along_x_axis(-steps)
end

String Freeze Modifier

The unary minus operator can also be used in a much more obscure way with a string. It will return a frozen (possibly preexisting) version of the string.

> food = 'taco'
=> "taco"
> food.frozen?
=> false
> other = -food
=> "taco"
> other.frozen?
=> true
> food.object_id
=> 360
> other.object_id
=> 380
> another = -food
=> "taco"
> another.object_id
=> 380

References