首页 » Ruby » Ruby学习笔记(17)_冒号用法

Ruby学习笔记(17)_冒号用法

原文 http://blog.csdn.net/slowsnowscar/article/details/78325902

2017-10-24 11:20:44阅读(205)

What is the difference between:

1) abc:

2) :xyz

3) Abc::Xyz

4) abc: :xyz

5) abc: xyz

6) :abc => xyz

Answer:

1) You can’t use abc: alone. See 4) for reason.

2) :xyz is a symbol literal. It’s very similar to “xyz”, except that :xyz is immutable, while “xyz” is mutable, and there is always only one :xyz in the memory (maybe this is no longer true because Ruby 2.2 introduces symbol GC?)

:xyz.class  #=> Symbol
:xyz.to_s  #=> "xyz"
"xyz".to_sym  #=> :xyz
a = :xyz
b = :xyz
a.object_id == b.object_id  #=> true

3.Abc::Xyz is very common. That’s the way you refer to the inner class/module/constant Xyz of class/module Abc. :: can but should not be used to call class/module methods.

4) abc: :xyz
Before Ruby 2.0 abc: :xyz can only appear as arguments passed to method calls. As an argument, this is a hash or part of a hash. The following 4 expressions are the same:

p abc: :xyz, foo: :bar  #=> prints {:abc => :xyz, :foo => :bar}
p(abc: :xyz, foo: :bar)  #=> prints {:abc => :xyz, :foo => :bar}
p({abc: :xyz, foo: :bar})  #=> prints {:abc => :xyz, :foo => :bar}
p({:abc => :xyz, :foo => :bar})  #=> prints {:abc => :xyz, :foo => :bar}

As arguments, the curly braces of hashes can be omitted. And when the keys of a hash are symbols, the colon can be moved behind the symbol, and the fat arrow => can be omitted. This makes hashes look more like JSON objects.

5)abc: xyz

xyz = "just a test"
hash = {abc: xyz} #hash key is symbol, value is string. 

6) :abc => xyz

Same as 5)

xyz = "just a test"
hash = {:abc => xyz} # same with (5), just another representation

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹