Understand the marker in Ruby (Understanding Ruby Symbols)

xiaoxiao2021-04-09  373

Understanding Ruby Symbols) Original Source: http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols Translation: SunInny At gmail.com Sign in Ruby is a fan . We use her, but most people don't really understand her. What is a sign? Simply, the logo is a thing you use to represent the name or string. This can be attributed to an efficient description name - generating a single string for each name instance, which saves space. Dr. Jones Jones (Dr. Dr Jones) is a psychologist. He usually uses the words Lenovo test to diagnose patients, and use ruby ​​to record everything. His first patient why came here: DR J: Red Why: Ruby Dr J: TRANSPORTATION why: Rails DR J: CHUNKY why: Bacon Jones cres a hash to store these data: why = {"red" = > "Ruby", "transportation" => "rails", "chunky" => "Bacon"} The problem is after providing hundreds of words Lenovo trials, Dr. Jones began to realize that he used to exhaust memory! So Jones in IRB Test:> Patient1 = {"Ruby" => "}> patient2 = {" Ruby "=>" programming "}> patient1.Each_key {| key | Puts key.object_id.to_s} 211006> patient2.each_key { | Key | Puts Key.Object_id.to_s} 203536 We see, each time he creates a hash to store information, Ruby has established a new string object for each key in different memory locations. Fortunately, we have other methods. Use the flag to break through the string, during a Ruby session, the same name is used to initialize only initialization and then exist in memory. When you need to reuse the string to indicate other things, the flag is flexible. During Dr. Jones, we can observe directly:> patient1 = {: ruby ​​=> "}> patient2 = {: Ruby =>" Programming "}> patient1.each_key {| key | PUTS key.Object_ID. TO_S} 3918094> Patient2.each_key {| key | puts key.object_id.to_s} 3918094 By using the flag, in the Lenovo trial we use a single memory address to represent "Ruby" words. Over time, this saves a lot of space. Other applications of the logo whenever, as long as you reusing a word to repeat other things, the logo can be used. Whether it is a key in the hash, or a method in the HTTP query. In the latest, the greatest web framework - Ruby On Rails is applied to the flag.

转载请注明原文地址:https://www.9cbs.com/read-133219.html

New Post(0)