Ruby journey (7) array and hash

Source: Internet
Author: User

Ruby supports arrays and hash. Both arrays and hash are accessed through indexes. The difference is that arrays are indexed by numbers, while hash indexes can be any object, therefore, the array access speed is faster (direct positioning), while hash is more flexible, and the search element speed is faster (hashAlgorithmLocate the index without traversing ).

In Ruby, arrays and hash can accommodate different objects, because this is determined by the ruby language (non-strong language, derived from a single object)

A common method of array is <the function of this method is to add an element to the array.

Sample

Class Myclass
Def To_s
Return   " Leeclass "
End
End


Arr =   % W [How are you.] # The same as arr = ["how", "are", "you."]
Arr <   " I'm "   # Append a Element
Arr < Myclass. New

Arr. Each do | Item |
If Item. Class . To_s.upcase ! =   " String "
Print   " # {Item}, type: # {item. Class} "
Else
Print Item +   "   "
End
End

# Output: How are you. I'm leeclass, type: myclass

 

Hash sample

Class Myclass
Def To_s
Return   " Hallo "
End
End

MC = Myclass. New
Hash = {
: Maozedong => " Laoda " ,
: Zhouenlai => " Laoer " ,
: Jiangjieshi =>   " Fool " ,
MC => MC
}


Puts hash [: Maozedong]. Class . To_s # Output string
Puts hash [: Maozedong] # Output laoda

Puts hash [MC]. Class . To_s # Output myclass
Puts hash [MC] # Output Hallo because the puts method default calling to_s

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.