0
0
RubyHow-ToBeginner · 2 min read

Ruby How to Convert String to Symbol Easily

In Ruby, convert a string to a symbol by calling to_sym on the string, like "example".to_sym.
📋

Examples

Input"hello"
Output:hello
Input"user_name"
Output:user_name
Input"123abc"
Output:"123abc"
🧠

How to Think About It

To convert a string to a symbol, think of symbols as names or labels that Ruby uses internally. You take the string and tell Ruby to treat it as a symbol by using the to_sym method, which changes the string into a symbol form.
📐

Algorithm

1
Get the input string.
2
Call the <code>to_sym</code> method on the string.
3
Return the resulting symbol.
💻

Code

ruby
str = "example"
sym = str.to_sym
puts sym
Output
example
🔍

Dry Run

Let's trace converting the string "example" to a symbol.

1

Start with string

str = "example"

2

Convert to symbol

sym = str.to_sym # sym becomes :example

3

Print symbol

puts sym # outputs example

VariableValue
str"example"
sym:example
💡

Why This Works

Step 1: What is a symbol?

A symbol is a lightweight, immutable identifier often used as names or keys in Ruby.

Step 2: Using to_sym method

The to_sym method converts a string into its symbol equivalent.

Step 3: Why convert?

Symbols are faster and use less memory than strings when used repeatedly as identifiers.

🔄

Alternative Approaches

intern
ruby
"example".intern
The <code>intern</code> method is an alias for <code>to_sym</code>, so it works the same way.

Complexity: O(1) time, O(1) space

Time Complexity

Converting a string to a symbol is a constant time operation because it just creates or references a symbol.

Space Complexity

It uses constant space since symbols are stored once and reused.

Which Approach is Fastest?

Both to_sym and intern are equally fast since they do the same thing.

ApproachTimeSpaceBest For
to_symO(1)O(1)Clear and common method
internO(1)O(1)Alias of to_sym, same performance
💡
Use to_sym to convert strings to symbols quickly and clearly.
⚠️
Trying to convert a string to a symbol by just prefixing with a colon like :'string' without using to_sym.