简体   繁体   中英

What is the difference between : and “” in Ruby hashes?

I see some people using hash(es) like this:

end_points = { "dev" => "http://example.com"}

and in other places using this:

 end_points = { :dev => "http://example.com"}

What is the difference between these two approaches?

"" declares a String . : declares a Symbol . If you're using a hash, and you don't need to alter the key's value or keep it around for anything, use a symbol.

Check this out for a more elaborate explanation.

:dev is a Symbol, 'dev' is a String.

Most of the time, symbols are used but both are correct. Some read on the subject :

What are symbols and how do we use them?

Why use symbols as hash keys in Ruby?

In first case you use string in second you use symbol. Symbols are specific type in Ruby. In whole program there is only one instance of symbol, but string can have it many. Ie

> :sym.__id__
=> 321608
> :sym.__id__
=> 321608
> "sym".__id__
=> 17029680
> "sym".__id__
=> 17130280

As you see symbol always has the same ID what mean that it is always the same object, but string is every time new string in new place of memory. That's the case why symbols are more common as hash keys, it's simply faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM