ruby - Why is it important to create a method as a symbol? -


i'm trying understand extent of symbols in ruby. understand more faster , efficient use symbols keys opposed strings, how faster?

and understanding, when referencing methods has represented symbol, :to_i opposed to_i. purpose of this?

in ruby, symbol immutable string:

"hello " + "world" #=> "hello world" :hello_ + :world #=> nomethoderror: undefined method `+' :hello:symbol 

being immutable makes symbols safe , reliable reference, example:

 object.methods => [:new, :allocate, :superclass, #etc..] 

if ruby use strings here, users able modify strings, ruining future calls of object.methods. fixed making copies of strings each time method called, huge memory footprint.

in fact, since ruby knows symbols never going modified, saves each symbol once, no matter how many times declare it:

"hello".object_id #=> 9504940 "hello".object_id #=> 9565300  :hello.object_id #=> 1167708 :hello.object_id #=> 1167708 

this takes memory-saving potential of symbols further, allowing use symbol literals in code anywhere , everywhere little memory overhead.

so, round-about answer question: symbols can't modified, they're safer , more memory efficient; therefore, should use them whenever have string know shouldn't modified.

symbols used keys hashes because:

  1. you should never modify key of hash while it's in hash.
  2. hashes require literal referencing lot, ie my_hash[:test], it's more memory-efficient use symbols.

as method references: can't reference method directly, ie send(my_method()) because can't tell difference between passing method in , executing it. strings have been used here, since method's name never changes once defined, makes more sense represent name symbol.


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -