What is the colon operator in Ruby?

2019-01-02 21:46发布

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?

标签: ruby symbol
9条回答
来,给爷笑一个
2楼-- · 2019-01-02 22:37

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".

查看更多
老娘就宠你
3楼-- · 2019-01-02 22:47

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.

查看更多
forever°为你锁心
4楼-- · 2019-01-02 22:50

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.

查看更多
登录 后发表回答