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