string: What is the use of the symbols as hash keys in Ruby ?

string: What is the use of the symbols as hash keys in Ruby ?

Asked on October 26, 2018 in String.
Add Comment


  • 3 Answer(s)

       Using symbols save both the time and memory for the user:

        Symbols in Ruby is more essentially “immutable strings” .. meaning that they’ll not be modified, and it implies that constant image once documented again and again throughout our ASCII text file, is usually keep because the same entity, e.g. has constant object id.

        Strings on the opposite hand is more changeable, they’ll be modified anytime. this means that Ruby has to store every string you mention throughout our ASCII text file in it’s separate entity, e.g. if we’ve got a string “name” multiple times mentioned in your ASCII text file, Ruby has to store these beat separate String objects, as a result of they could amendment anon (that’s the character of a Ruby string)

    Answered on October 26, 2018.
    Add Comment

    It is better to use ruby with the string key differently.

    for ex:

    s = "foo"
    
    h = {}
    
    h[s] = "bar"
    
    s.upcase!
    
    h.rehash # must be called whenever a key changes!
    
    h[s] # => nil, not "bar"
    
    h.keys
    
    h.keys.first.upcase! # => TypeError: can't modify frozen string
    
    
    Answered on October 26, 2018.
    Add Comment

    Here is the list of advantages:

     -Styling: its the Ruby-way

     -slightly faster value look ups since hashing a symbol is equivalent to hashing an integer vs hashing a string.

     

    Answered on October 26, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.