typestar

Symbols in Ruby

Why Ruby has two kinds of string and when the lightweight one wins.

# a symbol is an immutable, interned name: one object per spelling
state = :ready
puts state
puts state.object_id == :ready.object_id

config = { host: "localhost", port: 8080 }
puts config[:host]
puts config.key?(:port)

# &:sym turns a symbol into a block that calls the named method
puts %w[ruby rails rack].map(&:length).inspect

How it works

  1. A :symbol is an immutable, interned name — one object per spelling.
  2. Symbol keys give hashes the terse host: literal syntax.
  3. &:length converts a symbol into a block that calls that method.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
332
Tokens
52
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 37 seconds.

Type this snippet

Step 3 of 3 in Variables & strings, step 3 of 29 in Language basics.

← Previous Next →

Symbols in other languages