2 thoughts on “[help] on symbol operators”

  1. Something is missing here…

    `::` is the “scope resolution operator.” It is used for accessing things nested in modules.

    [1] pry(main)> module A
    [1] pry(main)* module B
    [1] pry(main)* SOME_CONSTANT = 1
    [1] pry(main)* end
    [1] pry(main)* end
    [2] pry(main)> A.B
    NoMethodError: undefined method `B’ for A:Module
    from (pry):7:in `__pry__’
    [3] pry(main)> A:B
    NoMethodError: undefined method `A’ for main:Object
    from (pry):8:in `__pry__’
    [4] pry(main)> A::B
    => A::B
    [5] pry(main)> A::B.SOME_CONSTANT
    NoMethodError: undefined method `SOME_CONSTANT’ for A::B:Module
    from (pry):10:in `__pry__’
    [6] pry(main)> A::B:SOME_CONSTANT
    NoMethodError: undefined method `B’ for A:Module
    from (pry):11:in `__pry__’
    [7] pry(main)> A::B::SOME_CONSTANT
    => 1

    `:`, following the key definition in a hash, precedes the value for that key. **When using this syntax the key and value are both symbols.**

    [1] pry(main)> hash = { something: :other }
    => {:something=>:other}
    [2] pry(main)> hash.keys.first
    => :something
    [3] pry(main)> hash.keys.first.class
    => Symbol
    [5] pry(main)> hash[hash.keys.first]
    => :other
    [4] pry(main)> hash[hash.keys.first].class
    => Symbol

    The use above was a syntax improvement for hash creation. Below we can compare the old syntax with the new.

    [6] pry(main)> { :something => :other } == { something: :other }
    => true

    Reply

Leave a Comment