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
- A
:symbolis an immutable, interned name — one object per spelling. - Symbol keys give hashes the terse
host:literal syntax. &:lengthconverts a symbol into a block that calls that method.
Keywords and builtins used here
puts
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.
Step 3 of 3 in Variables & strings, step 3 of 29 in Language basics.