-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsymbol.rb
More file actions
20 lines (17 loc) · 1.38 KB
/
Copy pathsymbol.rb
File metadata and controls
20 lines (17 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Symbol
# In Ruby, a symbol is a lightweight, immutable identifier that is often used to represent names or labels.
# Symbols are created by prefixing a string with a colon (`:`). For example, `:my_symbol` is a symbol.
# Symbols are unique and can be used as keys in hashes or as method names.
# They are more memory-efficient than strings because they are stored only once in memory, regardless of how many times they are used in the program.
# Example of symbol usage
my_symbol = :hello_world # symbol can store in a variable just like string
puts my_symbol # Output: hello_world
puts my_symbol.class # Output: Symbol
# Or we can use symbol literals directly without storing them in a variable
puts :ruby_is_fun # Output: ruby_is_fun
puts :ruby_is_fun.class # Output: Symbol
# Why use symbols instead of strings (in some cases)?
# 1. Memory Efficiency: Symbols are stored only once in memory, while each string is stored separately. This can save memory when you have many instances of the same identifier.
# 2. Performance: Comparing symbols is faster than comparing strings because symbols are immutable and unique, while strings can be mutable and may require more complex comparisons.
# 3. Readability: Symbols can make code more readable by clearly indicating that a value is meant to be an identifier rather than a piece of data.
# But for more simple case use regular like variable and string