2007年1月9日星期二

Symbol and String


A Symbol is about the most basic Ruby object you can create. It's just a name and an internal ID. Symbols are useful becase a given symbol name refers to the same object throughout a Ruby program.In Rails,we usually use this point,such as ":action=>welcome" and so on. If you wanna get the corresponding symbol of a given string,String.intern will be.

name ="allen"

puts :allen
#=>"allen"
puts name
#=>"allen"

puts :allen.object_id
#=>190498
puts name.intern.object_id
#=>190498
puts name.object_id
#=>21723660




In Rails, we can see the symbol around web application code.Let's think about it!
Hem.......because symbol don't allocate another memory,it doesn't like string.

puts "allen".object_id
#=>21723550
puts "allen".object_id
#=>21723490
puts :allen.object_id
#=>190498
puts :allen.object_id
#=>190498

没有评论: