🎓 A1Learner
🔍
0 of 34 lessons completed

Ruby Symbols in Depth

Symbols name things inside a program, and the beginner course used them as hash keys. This lesson compares symbol keys with string keys and turns symbols into blocks.

Symbol keys beside string keys

One hash can hold both key kinds at once. The symbol key :name and the string key "name" stay separate entries.

scores = { name: "Ana", "name" => "Ben" }
puts scores[:name]
puts scores["name"]
puts scores.length

Turning a symbol into a block

The &:upcase shape builds a block from the symbol. Each item receives the method the symbol names.

words = ["red", "blue"]
p words.map(&:upcase)

Making a symbol with to_sym

to_sym turns a string into the symbol with the same name. The new symbol then works as a hash key.

key = "status".to_sym
settings = { status: "ready" }
puts settings[key]

Calling a method by name with send

send takes a symbol and calls the method it names. The same string answers two calls this way.

word = "ruby"
puts word.send(:upcase)
puts word.send(:length)

Example

tags = ["sale", "new", "hot"]
p tags.map(&:upcase)
key = "count".to_sym
counts = { count: 3 }
puts counts[key]

Key points

  • A symbol key and a string key are different keys in the same hash.
  • &:name turns a symbol into a block that calls that method.
  • to_sym makes a symbol from a string.
  • send calls a method whose name is given as a symbol.

In this example, &:upcase turns the symbol into a block, so map capitalises every tag. The string count becomes a symbol through to_sym. That symbol then reads the value stored under the :count key.

Note

A symbol is written with a colon before its name, as in :status.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does ["a", "bb"].map(&:length) give?