By LuxuryMode


2011-06-14 00:30:00 8 Comments

When I say { :bla => 1, :bloop => 2 }, what exactly does the : do? I read somewhere about how it's similar to a string, but somehow a symbol.

I'm not super-clear on the concept, could someone enlighten me?

9 comments

@Frank Carnovale 2018-08-23 13:43:37

All these answers omit one extra tantalising detail.. if you stringify the symbol :foo, you get.. guess what.. the string "foo". Hence

irb(main):025:0>
irb(main):026:0> :foo
=> :foo
irb(main):027:0> "#{:foo}"
=> "foo"
irb(main):028:0>
irb(main):029:0> 'foo' <=> :foo
=> nil
irb(main):030:0> 'foo' <=> :foo.to_s
=> 0
irb(main):031:0>

Hence.. for Perl programmers.. it's Ruby's answer to the 'bare word'.

@Devin Huang 2016-07-24 12:48:56

In ruby each object has an unique object identifier, if you write puts "hello".object_id in your irb and hit return for 2 different times, you will get 2 different returning value,but if you write :hello.object_id 2 times you will only get the same one returning value. That should have explained the difference.

@Cesar Jr Rodriguez 2016-10-03 03:07:03

Basically the colon operator is for assign a symbol

@Charles 2015-07-23 21:36:17

If you use :foo => bar, foo will be a symbol. The benefit to symbols is that they are unique. When you call on an item in the hash, you do hash[:foo].

Symbols require less memory than strings, which also makes them useful if you want to make your program a little faster.

@shyan1 2013-09-23 08:45:46

There're some quotes from the famous book Agile Web Development with Rails, which may be helpful to understand the symbol as well :

Rails uses symbols to identify things. In particular, it uses them as keys when naming method parameters and looking things up in hashes.

redirect_to :action => "edit", :id => params[:id]

You can think of symbols as string literals that are magically made into constants. Alternatively, you can consider the colon to mean "the thing named", so :id is "the thing named id".

@the Tin Man 2013-02-23 17:28:21

Just to demonstrate some of the things mentioned in the answers:

require 'benchmark'

n = 1_000_000

print '"foo".equal? "foo" -> ', ("foo".equal? "foo"), "\n"
print '"foo" == "foo"     -> ', ("foo" == "foo"    ), "\n"
print ':foo.equal? :foo   -> ', (:foo.equal? :foo  ), "\n"
print ':foo == :foo       -> ', (:foo == :foo      ), "\n"

Benchmark.bm(10) do |b|
  b.report('string')     { n.times { "foo".equal? "foo" }}
  b.report('str == str') { n.times { "foo" == "foo"     }}
  b.report('symbol')     { n.times { :foo.equal? :foo   }}
  b.report('sym == sym') { n.times { :foo == :foo       }}
end

Running it outputs:

"foo".equal? "foo" -> false
"foo" == "foo"     -> true
:foo.equal? :foo   -> true
:foo == :foo       -> true

So, comparing a string to a string using equal? fails because they're different objects, even if they are equal content. == compares the content, and the equivalent checks with symbols are much faster.

                 user     system      total        real
string       0.370000   0.000000   0.370000 (  0.371700)
str == str   0.330000   0.000000   0.330000 (  0.326368)
symbol       0.170000   0.000000   0.170000 (  0.174641)
sym == sym   0.180000   0.000000   0.180000 (  0.179374)

Both symbol tests are basically the same as far as speed. After 1,000,000 iterations there's only 0.004733 second difference, so I'd say it's a wash between which to use.

@melvynkim 2014-03-07 12:44:18

Extremely helpful! On my system, == resulted faster than .equal? for both string and symbol comparisons. Symbol comparison resulted 3+ times faster than string comparisons.

@Dhruva Sagar 2011-06-14 04:13:16

If you are familiar with Java, you might be aware that Strings in Java are immutable. Symbols are similar in that sense in Ruby. They are immutable, i.e., any number of occurances of a particular symbol :symbol will map to only a single memory address. And, hence, it is recommended to use symbols wherever possible since it optimizes memory usage.

@Dhruva Sagar 2012-08-21 07:03:23

The fact that symbols are immutable ensures that they are always the same instance throughout your application and hence they are guaranteed to be the same object. Check these references : troubleshooters.com/codecorn/ruby/symbols.htm robertsosinski.com/2009/01/11/… You'll find loads more if you google.

@smartnut007 2012-08-21 19:25:02

I am talking about your analogy to Java. Java Strings are not analogous to symbols. Java string literals are but not all strings.

@Dhruva Sagar 2012-08-22 10:47:10

Perhaps my statement wasn't clear enough. They are analogous to each other only with respect to the fact that they are immutable.

@Rafael Bugajewski 2016-01-04 10:47:56

@DhruvaSagar: The analogy would be better if you used Objective C’s NSString. There "foo" will always be equal to "foo", because internally strings that are the same are just pointed to. The answer would still be confusing, though.

@kindall 2011-06-14 00:34:50

It's a symbol. Basically, you are saying that the two elements of the hash have keys bla and bloop, much as if you had used the strings "bla" and "bloop". However, they take up less memory than strings and are easier to type.

@nunopolonia 2011-06-14 00:34:21

Symbols are a way to represent strings and names in ruby.

The main difference between symbols and strings is that symbols of the same name are initialized and exist in memory only once during a session of ruby.

They are useful when you need to use the same word to represent different things

@Chris Jester-Young 2011-06-14 00:33:20

:foo is a symbol named "foo". Symbols have the distinct feature that any two symbols named the same will be identical:

"foo".equal? "foo"  # false
:foo.equal? :foo    # true

This makes comparing two symbols really fast (since only a pointer comparison is involved, as opposed to comparing all the characters like you would in a string), plus you won't have a zillion copies of the same symbol floating about.

Also, unlike strings, symbols are immutable.

@onmyway133 2014-09-19 04:55:09

just wonder why literal string does not support string interning ?

@Chris Jester-Young 2014-09-19 05:35:03

@onmyway133 Because Ruby's strings are mutable. Interning only applies to immutable values.

@Arc676 2016-02-20 09:11:43

a) Why is "foo".equal? "foo" false? b) Can you refer to a symbol anywhere, essentially making them like global variables?

@Chris Jester-Young 2016-02-20 15:11:18

@Arc676 1. equal? in Ruby does identity comparison. Each string literal, like "foo", creates a new string instance. It works that way because strings in Ruby are mutable. 2. Symbols are global, but more like global constants than global variables, since symbols do not have state. Thus using symbols is not an antipattern in the way that global variables are.

@Filip Bartuzi 2017-05-10 13:58:21

@Arc676 "foo" == "foo" # => true

Related Questions

Sponsored Content

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

24 Answered Questions

[SOLVED] How to write a switch statement in Ruby

20 Answered Questions

[SOLVED] Calling shell commands from Ruby

  • 2008-08-05 12:56:52
  • CodingWithoutComments
  • 507406 View
  • 1023 Score
  • 20 Answer
  • Tags:   ruby shell interop

10 Answered Questions

[SOLVED] How to convert a string to lower or upper case in Ruby

16 Answered Questions

19 Answered Questions

[SOLVED] What is attr_accessor in Ruby?

  • 2010-12-06 21:07:06
  • dennismonsewicz
  • 446526 View
  • 988 Score
  • 19 Answer
  • Tags:   ruby

25 Answered Questions

[SOLVED] Check if a value exists in an array in Ruby

  • 2009-12-31 17:49:03
  • user211662
  • 811376 View
  • 1254 Score
  • 25 Answer
  • Tags:   ruby arrays

11 Answered Questions

[SOLVED] How to understand symbols in Ruby

  • 2010-02-26 13:22:05
  • Kezzer
  • 37974 View
  • 81 Score
  • 11 Answer
  • Tags:   ruby symbols

14 Answered Questions

[SOLVED] A concise explanation of nil v. empty v. blank in Ruby on Rails

  • 2009-05-19 22:51:36
  • Arrel
  • 299638 View
  • 1095 Score
  • 14 Answer
  • Tags:   ruby-on-rails ruby

2 Answered Questions

[SOLVED] Ruby ampersand colon shortcut

  • 2009-12-25 11:35:57
  • Allan Grant
  • 91817 View
  • 316 Score
  • 2 Answer
  • Tags:   ruby

Sponsored Content