2

I heard that two symbols with the same name create only one memory area, but two strings with the same content create two memory areas.

  • What is the use of symbols?
  • Is symbol like a variable? If so, how can I assign a value to a symbol?
  • If I allocate memory only once for symbols with the same name, what am I doing with the symbols?
sawa
  • 165,429
  • 45
  • 277
  • 381
suresh
  • 139
  • 11
  • 1
    Possible duplicate of [Understanding Symbols In Ruby](http://stackoverflow.com/questions/2341837/understanding-symbols-in-ruby) – M. Karim Jul 07 '16 at 04:14
  • So, the only use is if i use two hashes with same key, I need to use symbol instead string. Is there any other use with symbols ? – suresh Jul 07 '16 at 04:19
  • 1
    Have a look; it is helpful [ruby-similarity-and-difference-between-symbol-and-string-with-facts](https://cbabhusal.wordpress.com/2015/09/16/ruby-similarity-and-difference-between-symbol-and-string-with-facts/) – Shiva Jul 07 '16 at 04:24

3 Answers3

4

Ok, so the misunderstanding probably stems from this:

A symbol is not a variable, it is a value. like 9 is a value that is a number.

A symbol is a value that is kinda of roughly a string... it's just not a string that you can change... and because you can't change it, we can use a shortcut -> all symbols with the same name/value are stored in the same memory-spot (to save space).

You store the symbol into a variable, or use the value somewhere - eg as the key of a hash.... this last is probably one of the most common uses of a symbol.

you make a hash that contains key-value pairs eg:

thing_attrs = {:name => "My thing", :colour => "blue", :size => 6}
thing_attrs[:colour]  # 'blue'

In this has - the symbols are the keys you can use any object as a key, but symbols are good to use as they use english words, and are thus easy to understand what you're storing/fetching... much better than, say numbers. Imagine you had:

thing_attrs = {0 => "My thing", 1 => "blue", 2 => 6}
thing_attrs[1] # => "blue"

It would be annoying and hard to remember that attribute 1 is the colour... it's much nicer to give names that you can read when you're reading the code. Thus we have two options: a string, or a symbol.

There would be very little difference between the two. A string is definitely usable eg:

thing_attrs = {"name" => "My thing", "colour" => "blue", "size" => 6}
thing_attrs["colour"]  # 'blue'

except that as we know... symbols use less memory. Not a lot less, but enough less that in a large program, over time, you will notice it. So it has become a ruby-standard to use symbols instead.

Taryn East
  • 27,486
  • 9
  • 86
  • 108
  • In your example, using symbols it creates three symbol objects. If I use the strings, that time also it creates three objects. So, why I have to use symbols instead string. – suresh Jul 07 '16 at 04:39
  • 2
    @suresh, in the above example, yes you get the same number of objects using strings or symbols. However, suppose you have a thousand hashes, all with the same keys but different values. Maybe each stores user data for a different user. If you use strings for the keys you will have a thousand copies of each key stored in memory. If you use symbols you will only have one. – lwassink Jul 07 '16 at 04:44
  • If I store that into a one variable. I can use that variable in thousand hashes. This time also it allocates memory for same time like a symbols. So, what is the use ? – suresh Jul 07 '16 at 04:49
  • 1
    @suresh yeah you could do that but why bother when you can use symbols instead which do that anyway? – Sagar Pandya Jul 07 '16 at 05:46
  • You can use a named-variable instead of a symbol... which uses 2 locations, one to store the value that is in the variable and one to store the variable-name that is pointing at the value... so the symbol is a way of doing just that but only using one memory location. It is a small memory-save that really only is useful when you have a large codebase – Taryn East Jul 07 '16 at 05:54
  • 1
    Imagine that you are iterating through a set of 10,000 Users, looking at each of their attributes.... lets say that a user has 20 attributes... that's 200,000 keys in play... or 20 used over and over... – Taryn East Jul 07 '16 at 05:55
  • 2
    If you write this in C: for (int i = 0; i < 10; i++) than any C programmer understands what you mean. If you write this in Ruby: { :name => 'apple', :color => 'blue'}, or, { name: 'apple', color: 'blue' } than any Ruby programmer understands what you mean. The more complicated you make it, the more effort it will take to understand. Symbols are elegant communication to the reader of the source. – Jim Flood Jul 07 '16 at 07:39
  • 2
    Also, this isn't just about memory, it's about code readability. If you use variables, you need to declare them ahead of time, which adds unnecessary lines of code. I think that's at least as good an argument as the memory savings. Also, if you want to change the hash keys and you use symbols you only have to change one thing. If you use variables you have to remember to change two things. (I suppose you could define the variables as you use them, but think of how messy your hashes will look.) – lwassink Jul 08 '16 at 03:54
3

A Symbol is the most basic Ruby object you can create. It's just a name and an internal ID. Symbols are useful because a given symbol name refers to the same object throughout a Ruby program. Symbols are more efficient than strings. Two strings with the same contents are two different objects, but for any given name there is only one Symbol object. This can save both time and memory.

# p039symbol.rb  
# use the object_id method of class Object  
# it returns an integer identifier for an object  
puts "string".object_id  
puts "string".object_id  
puts :symbol.object_id  
puts :symbol.object_id  

>ruby p039symbol.rb  
21066960  
21066930  
132178  
132178  
>Exit code: 0
Kaushlendra Tomar
  • 1,410
  • 10
  • 16
  • This is okay. But what I am going to do with symbols in ruby program. Is there any real world example In here you can use symbols like that ? – suresh Jul 07 '16 at 04:27
3

I find it most helpful to think of symbols as strings without all the fancy string features. Their main use is as the name of other things in your program. For example, say you have a hash of user information. You could do

user = { 'name' => 'Tim', 'age' => 20 }

Here the hash keys are strings. This is fine, but it's really overkill. Strings have lots of fancy methods like substitution and smart capitalization, and they are mutable (i.e. string objects can be changed in place). You are never going to change hash keys, so you don't need any of that. Thus, it's better just to use symbols

user = { :name => 'Tim', :age => 20 }

Another place symbols show up is referring to class methods. Say I have the following class

class Foo
  def initialize(bar)
    @bar = bar
  end
end

If I need access to the value of @bar from outside of Foo I need to add a getter method to Foo. That would look like this

class Foo
  def initialize(bar)
    @bar = bar
  end

  def bar
    bar
  end
end

However, this is a pretty common thing to want to do, so ruby provides shorthand as follows

class Foo
  attribute_reader :bar

  def initialize(bar)
    @bar = bar
  end
end

This tells Foo to create for us the method we added by hand in the previous version. As you can see, we refer to the @bar variable using a symbol.

In answer to your second question, no, a symbol is not a variable. You can't "assign it a value." However, as you can see, symbols can sometimes be used to refer to variables.

lwassink
  • 1,595
  • 13
  • 16
  • 2
    Your second sentence is really the most important sentence on this entire page. `Integer` is the type for integral numbers, `Rational` is the type for integer ratios, `String` is the type for text, and `Symbol` is the type for labels of things. *That's* what's important. Whether or not one is mutable and the other is not, and what methods it has or doesn't have, the fact that it happens to be implemented as an entry into the actual symbol table of the compiler, is a *consequence* of what it's *for*, not a defining characteristic. – Jörg W Mittag Jul 07 '16 at 21:53
  • 1
    @Jorg W Mittag, a good point, though I do think it's important to explain _why_ symbols make good labels, once you've explained that that's what they're there for. – lwassink Jul 08 '16 at 03:57