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

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值