본문 바로가기
2014.04.05 19:33

Ruby Symbols

조회 수 6291 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print

http://rubylearning.com/satishtalim/ruby_symbols.html


A symbol looks like a variable name but it's prefixed with a colon. Examples - :action:line_items. You don't have to pre-declare a symbol and they are guaranteed to be unique. There's no need to assign some kind of value to a symbol - Ruby takes care of that for you. Ruby also guarantees that no matter where it appears in your program, a particular symbol will have the same value.

Alternatively, you can consider the colon to mean "thing named" so :id is "the thing named id." You can also think of :id as meaning the name of the variable id, and plain id as meaning the value of the variable.

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.

Refer the example: p039symbol.rb below

  1. # p039symbol.rb  
  2. # use the object_id method of class Object  
  3. # it returns an integer identifier for an object  
  4. puts "string".object_id  
  5. puts "string".object_id  
  6. puts :symbol.object_id  
  7. puts :symbol.object_id  

The output when I ran the program on my PC was:

  1. >ruby p039symbol.rb  
  2. 21066960  
  3. 21066930  
  4. 132178  
  5. 132178  
  6. >Exit code: 0  

Therefore, when do we use a string versus a symbol?

  • If the contents (the sequence of characters) of the object are important, use a string
  • If the identity of the object is important, use a symbol

Ruby uses symbols, and maintains a Symbol Table to hold them. Symbols are names - names of instance variables, names of methods, names of classes. So if there is a method called control_movie, there is automatically a symbol :control_movie. Ruby's interpreted, so it keeps its Symbol Table handy at all times. You can find out what's on it at any given moment by calling Symbol.all_symbols.

A Symbol object is created by prefixing an operator, string, variable, constant, method, class, module name with a colon. The symbol object will be unique for each different name but does not refer to a particular instance of the name, for the duration of a program's execution. Thus, if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

This can be illustrated by this simple program - p039xsymbol.rb:

  1. # p039xsymbol.rb  
  2. class Test  
  3.   puts :Test.object_id.to_s  
  4.   def test  
  5.     puts :test.object_id.to_s  
  6.     @test = 10  
  7.     puts :test.object_id.to_s  
  8.   end  
  9. end  
  10. t = Test.new  
  11. t.test  

The output when I ran the program on my PC was:

  1. >ruby p039xsymbol.rb  
  2. 116458  
  3. 79218  
  4. 79218  
  5. >Exit code: 0  

Here is another example - p039xysymbol.rb:

  1. # p039xysymbol.rb  
  2. know_ruby = :yes  
  3. if know_ruby == :yes  
  4.   puts 'You are a Rubyist'  
  5. else  
  6.   puts 'Start learning Ruby'  
  7. end  

The output is:

  1. >ruby p039xysymbol.rb  
  2. You are a Rubyist  
  3. >Exit code: 0  

In this example, :yes is a symbol. Symbols don't contain values or objects, like variables do. Instead, they're used as a consistent name within code. For example, in the preceding code you could easily replace the symbol with a string, as in example - p039xyzsymbol.rb

  1. # p039xyzsymbol.rb  
  2. know_ruby = 'yes'  
  3. if know_ruby == 'yes'  
  4.   puts 'You are a Rubyist'  
  5. else  
  6.   puts 'Start learning Ruby'  
  7. end  

This gives the same result, but isn't as efficient. In this example, every mention of 'yes' creates a new object stored separately in memory, whereas symbols are single reference values that are only initialized once. In the first code example, only :yes exists, whereas in the second example you end up with the full strings of 'yes' and 'yes' taking up memory.

We can also transform a String into a Symbol and vice-versa:

  1. puts "string".to_sym.class # Symbol  
  2. puts :symbol.to_s.class    # String  

Symbols are particularly useful when creating hashes and you want to have a distinction between keys and values. Please refer to Using Symbols as Hash Keys for a practical example.





Title
List of Articles
번호 제목 글쓴이 날짜 조회 수
31 Different Ways to Set Attributes in ActiveRecord (attribute, create, update, validation) Hojung 2015.05.24 1268
30 Ruby Style Guide Hojung 2015.02.05 1605
29 Refresh content automatically after some period time on Rails Hojung 2015.01.22 2210
28 Install ruby-filemagic on Mac (brew, libmagic) Hojung 2014.12.03 1475
27 Byte manipulation in Ruby Hojung 2014.12.03 1434
26 How to use Github for your project file Hojung 2014.09.24 1051
25 Ruby map, each, collect, inject, reject, select quick reference Hojung 2014.06.10 1814
24 Difference between collect, select, map and each in ruby Hojung 2014.06.10 1296
23 remove nil from array (compact, compact!) Hojung 2014.06.10 1603
22 remove child association model when parent removed (rails-dependent-destroy) Hojung 2014.06.03 1661
21 deploying cron jobs with whenever gem Hojung 2014.06.01 1703
20 Get list of a class' instance methods Hojung 2014.06.01 1364
19 Optional method parameters in Ruby Hojung 2014.05.29 1486
18 Best Ruby On Rails Content Management Systems (CMS) Hojung 2014.04.26 2682
17 The simple way to print exceptions in Ruby Hojung 2014.04.07 1516
» Ruby Symbols Hojung 2014.04.05 6291
15 What is the difference between a Symbol and String? Hojung 2014.04.05 1493
14 install Rbenv, ruby and rails Hojung 2014.03.22 1669
13 HTTP Posts in Ruby Hojung 2014.03.14 1664
12 optparse: mandatory and optional arguments example Hojung 2014.03.14 2351
Board Pagination ‹ Prev 1 2 Next ›
/ 2

Designed by sketchbooks.co.kr / sketchbook5 board skin

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5