Ruby collection and container object usage detailed

Source: Internet
Author: User
Tags arrays hash join new set

Arrays (array), hash (hash). The items in the array are in order, and you can get the corresponding items with the index number. The items in the hash are paired, there is a key in a pair and a corresponding value. The value of the project can be obtained by using the key of the project.

Any Ruby object can be a hash key or value, but note that the key must be unique in the hash. Hash is also called dictionaries or associative arrays in other languages.

The array is similar to the hash. In a sense the array is a hash, except that its key is a sequential integer. The hash has a sense of array, except that the index can be anything.

Do an experiment:

Array = ["Ruby", "Diamond", "Emerald"]
hash = {0 => "Ruby", 1 => "Diamond", 2 => "Emerald"}
Puts Array[0] # Ruby
Puts Hash[0] # Ruby
And do an experiment:

hash = {"Red" => "Ruby", "White" => "Diamond", "green" => "Emerald"}
Hash.each.with_index {| ( Key,value), i|
Puts "Pair #{i} is: #{key}/#{value}"
}
The output is:

Pair 0 Is:red/ruby
Pair 1 Is:white/diamond
Pair 2 Is:green/emerald
Array

Create a new array

There are several ways:

Array.new method
Literal builder: []
Array top-level method
%w{...},%i{...}
Array.new

A = Array.new
To set the size and content of an array:

>> Array.new (3)
=> [Nil, nil, nil]
>> array.new (3, "abc")
=> ["ABC", "ABC", "ABC"]
Provides a block of code:

>> n = 0
=> 0
>> Array.new (3) {n + + 1; n * 10}
=> [10, 20, 30]
And do an experiment:

>> a = array.new (3, "abc")
=> ["ABC", "ABC", "ABC"]
>> A[0] << "def"
=> "ABCdef"
>> puts A[1]
ABCdef
=> Nil
The ABC above is the same thing. Want to be different words need this:

Array.new (3) {"ABC"}
Literal builder

The array literal constructor is: []

A = []
You can add objects directly to the array when you create them:

A = [1,2, "three", 4,[]]
Array method

>> string = ' Hello '
=> "Hello"
>> string.respond_to? (: To_ary)
=> false
>> string.respond_to? (: To_a)
=> false
>> Array (String)
=> ["Hello"]
>> def string.to_a
>> Split (//)
>> End
=>: To_a
>> Array (String)
=> ["H", "E", "L", "L", "O"]
%w and%w

>>%w{I Love You}
=> ["I", "Love", "You"]
%w can be parsed with double quotes.

%i and%i

An array of symbols.

>>%i{a b C}
=> [: A,: B,: c]
>> w = "Love"
=> "Love"
>>%i{"#{w}"}
=> [: "\" Love\ "]
Try_convert

>> obj = object.new
=> #<object:0x007fa7e39e0ce0>
>> Array.try_convert (obj)
=> Nil
>> def obj.to_ary
>> [1,2,3]
>> End
=>: To_ary
>> Array.try_convert (obj)
=> [1, 2, 3]
>> def obj.to_ary
>> "Not a array!"
>> End
=>: To_ary
>> Array.try_convert (obj)
Typeerror:can ' t convert Object to Array (Object#to_ary gives String)
From (IRB): 199:in ' Try_convert '
From (IRB): 199
From/usr/local/bin/irb:11:in ' <main> '
Insert, retrieve, delete an array item

To insert a project:

A = []
A[0] = "a"
A[0] is a syntactic sugar that is actually a method of calling, and taking off its icing should be:

a.[]= (0, "a")
Retrieve Item:

>> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> P a[2]
3
=> 3
A[2] is also a grammatical sugar, take off the icing should be:

A.[] (2)
Multiple items at once

>> a = ["Red", "orange", "yellow", "purple", "gray", "Indigo", "Violet"]
=> ["Red", "orange", "yellow", "purple", "gray", "Indigo", "Violet"]
>> a[3,2]
=> ["Purple", "gray"]
>> a[3,2] = "green", "blue"
=> ["Green", "blue"]
>> A
=> ["Red", "orange", "Yellow", "green", "Blue", "Indigo", "Violet"]
The slice method is the same as [].

>> A.values_at (0,3)
=> ["Red", "green"]
The beginning and end of an array

Unshift add an item to the front of the array:

>> a = [1,2,3]
=> [1, 2, 3]
>> a.unshift (0)
=> [0, 1, 2, 3]
Push will add the item at the end of the array:

>> a = [1,2,3]
=> [1, 2, 3]
>> A.push (4)
=> [1, 2, 3, 4]
You can also use <<, like this:

>> a << 5
=> [1, 2, 3, 4, 5]
Push can add multiple items.

Delete the items in the array with shift and pop:

>> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> popped = A.pop
=> 5
>> puts popped
5
=> Nil
>> p A
[1, 2, 3, 4]
=> [1, 2, 3, 4]
>> shifted = A.shift
=> 1
>> puts shifted
1
=> Nil
>> p A
[2, 3, 4]
=> [2, 3, 4]
Merging arrays

First try Concat:

>> [1,2,3].concat ([4,5,6])
=> [1, 2, 3, 4, 5, 6]
Concat will change the source array, if you want a new merged array, you can use the +:

>> a = [1,2,3]
=> [1, 2, 3]
>> B = A + [4,5,6]
=> [1, 2, 3, 4, 5, 6]
>> A
=> [1, 2, 3]
Replace with replace:

>> a = [1,2,3]
=> [1, 2, 3]
>> A.replace ([4,5,6])
=> [4, 5, 6]
>> A
=> [4, 5, 6]
Do an experiment to understand the difference between = and replace:

>> a = [1,2,3]
=> [1, 2, 3]
>> B = A
=> [1, 2, 3]
>> A.replace ([4,5,6])
=> [4, 5, 6]
>> b
=> [4, 5, 6]
>> a = [7,8,9]
=> [7, 8, 9]
>> b
=> [4, 5, 6]
Array transformation

Flatten, remove the hierarchy in the array, and in the argument you can specify the number of levels to remove:

>> array = [1,2,[3,4[5]],[6,[7,8]]]
=> [1, 2, [3, 0], [6, [7, 8]]]
>> Array.flatten
=> [1, 2, 3, 0, 6, 7, 8]
>> Array.flatten (1)
=> [1, 2, 3, 0, 6, [7, 8]]
>> Array.flatten (2)
=> [1, 2, 3, 0, 6, 7, 8]
Reverse Upside down:

>> [1,2,3].reverse
=> [3, 2, 1]
Join

>> ["abc", "Def", 123].join
=> "Abcdef123"
Parameters for join:

>> ["abc", "Def", 123].join (",")
=> "ABC, DEF, 123"
There's a way to merge:

>> A =%w{One Two three}
=> ["One", "two", "three"]
>> A * "-"
=> "One-two-three"
Remove Duplicates:

>> [1,2,3,3].uniq
=> [1, 2, 3]
Remove Nil:

>> zip_codes = ["06511", "08902", "08902", Nil, "10027",
"08902", Nil, "06511"]
=> ["06511", "08902", "08902", Nil, "10027", "08902", Nil, "06511"]
>> Zip_codes.compact
=> ["06511", "08902", "08902", "10027", "08902", "06511"]
Array query

A.size,a.length: Number of items
A.empty?: Blank?
A.include? (item): Is there a project?
A.count (item): How much is the project?
A.first (n=1): First few items
A.last (n=1): the latter several projects
A.sample (n=1): Random Items
Experiment:

>> A
=> ["One", "two", "three"]
>> A.first (n=1)
=> ["One"]
>> A.first (n=2)
=> ["One", "two"]
>> A.last (n=1)
=> ["Three"]
>> A.sample (n=1)
=> ["Two"]
>> A.sample (n=1)
=> ["One"]
Hash

First do an experiment, create a hash, according to the user's input, get the abbreviation of the region:

P_hash = {
"Beijing" => "BJ",
"Shanghai" => "SH",
"Guangzhou" => "GZ"
}

Print "Enter the name of the region:"
p = Gets.chomp
abbr = P_hash[p]
Puts "area abbreviation is #{abbr}"
Create Hash

Several ways to create a hash:

Literal builder: {}
Hash.new method
Hash. [] Method
Hash Top Method
Create a literal hash

Inside the brace is a hash item, each item has a key, and a corresponding value, which is connected by a => symbol, separated by a comma between the project and the project.

Hash.new

Hash. [] class method

>> hash["Beijing", "BJ", "Shanghai", "SH"]
=> {"Beijing" => "BJ", "Shanghai" => "SH"}
>> hash[[[1,2], [3,4], [5,6]]]
=> {1=>2, 3=>4, 5=>6}
Hash method

Hash method is a bit of a special behavior. When called, give it a blank array ([]) or nil, which returns a blank hash. Otherwise it would call To_hash on the argument, and if the array had no To_hash method, it would trigger an error.

Insert, retrieve, delete hash item

Add New item to hash

Using the []= method:

p_hash["Shandong"] = "SD"
Taking off the icing should be like this:

P_hash. []= ("Shandong", "SD")
The store can also:

P_hash.store ("Shandong", "SD")
Do an experiment:

>> h = hash.new
=> {}
>> h["a"] = 1
=> 1
>> h["a"] = 2
=> 2
>> puts h["a"]
2
=> Nil
Get value

With the [] method:

>> p_hash["Beijing"]
=> "BJ"
You can also use the Fetch method:

>> p_hash.fetch ("Beijing")
=> "BJ"
[] The difference from the fetch is that there is an exception when you fetch a key that does not exist, and [] returns nil.

>> P_hash.fetch ("Yunnan", "Unknown State")
=> "Unknown State"
Multiple key:

>> p_hash.values_at ("Beijing", "Shanghai")
=> ["BJ", "SH"]
Default hash value and behavior

This is the default scenario:

>> h = hash.new
=> {}
>> h["No such key!"]
=> Nil
To set the default value:

>> h = hash.new (0)
=> {}
>> h["No such key!"]
=> 0
Try this:

H = hash.new {|hash,key| Hash[key] = 0}
Again this:

>> h["New key!"]
=> 0
>> h
=> {"New key!" =>0}
Merge Hash

Update, destructive mergers:

>> H1 = {"Smith" => "John", "Jones" => "Jane"}
=> {"Smith" => "John", "Jones" => "Jane"}
>> H2 = {"Smith" => "Jim"}
=> {"Smith" => "Jim"}
>> h1.update (H2)
=> {"Smith" => "Jim", "Jones" => "Jane"}
>> puts h1["Smith"]
Jim
=> Nil
Merge, not destructive mergers:

>> H1 = {"Smith" => "John", "Jones" => "Jane"}
=> {"Smith" => "John", "Jones" => "Jane"}
>> H2 = {"Smith" => "Jim"}
=> {"Smith" => "Jim"}
>> h3 = H1.merge (H2)
=> {"Smith" => "Jim", "Jones" => "Jane"}
>> p h1["Smith"]
"John"
=> "John"
Hash variant

Select and Reject Elements

Select

>> h = hash[1,2,3,4,5,6]
=> {1=>2, 3=>4, 5=>6}
>> h.select {|k,v| k > 1}
=> {3=>4, 5=>6}
Reject

>> h.reject {|k,v| k > 1}
=> {1=>2}
KEEP_IF:

>> h
=> {1=>2, 3=>4, 5=>6}
>> h.keep_if {|k,v| k > 1}
=> {3=>4, 5=>6}
>> h
=> {3=>4, 5=>6}
DELETE_IF:

>> h
=> {3=>4, 5=>6}
>> h.delete_if {|k,v| k > 3}
=> {3=>4}
>> h
=> {3=>4}
Reversed

Invert

>> h = {1 => "one", 2 => "two"}
=> {1=> "One", 2=> "two"}
>> H.invert
=> {"One" =>1, "two" =>2}
Note that the key must be unique.

>> h = {1 => "one", 2 => "more than 1", 3 => "more than 1"}
=> {1=> "One", 2=> "more than 1", 3=> "more than 1"}
>> H.invert
=> {"One" =>1, "more than 1" =>3}
Empty

Clear

>> {1 => "one", 2 => "two"}.clear
=> {}
Replace

>> {1 => "one", 2 => "two"}.replace ({=> "ten", => "Twenty"})
=> {=> "ten", => "twenty"}
Query Hash

H.has_key? (1)
H.include? (1)
H.key? (1)
H.member? (1)
H.has_value? ("three")
H.value? ("three")
H.empty?
H.size
Hash as a parameter of the method

The last parameter in the list of parameters is a hash, not {}.

Add_to_city_datebase ("New York City",
State: "New York",
population:7000000,
Nickname: "Big Apple"
)
Methods should be defined like this:

def add_to_city_datebase (name, info)
c = city.new
C.name = Name
C.state = Info[:state]
C.population = info[:p opulation]
# ...
Named parameters

When you define a method, you do this:

>> def m (A:, B:)
>> P A,b
>> End
=>: M
>> m (a:1, B:2)
1
2
=> [1, 2]
Default parameters:

>> def m (A:1, B:2)
>> P A,b
>> End
=>: M
>> SELF.M
1
2
=> [1, 2]
>> m (a:10)
10
2
=> [10, 2]
You guess:

>> def m (A:1, B:2, **c)
>> P A,b,c
>> End
=>: M
>> m (x:1, Y:2)
1
2
{: X=>1,: Y=>2}
=> [1, 2, {: X=>1,: y=>2}]
>> def m (x, Y, *z, a:1, B:, **c, &block)
>> P X,y,z,a,b,c
>> End
=>: M
>> m (1,2,3,4,5,b:10,p:20,q:30)
1
2
[3, 4, 5]
1
10
{:p =>20,: q=>30}
=> [1, 2, [3, 4, 5], 1, ten, {:p =>20,: q=>30}]
Range

Range: Range

Contains (inclusion)--is the value given in a range?
Enumeration (enumeration)--a collection of a single set of items that can be obtained from a range
Create a range

Range.new:

>> r = range.new (1, 100)
=> 1..100
The inclusive range is created, and then a exclusive range is created, with three dots:

>> r = 1...100
=> 1...100
Range-inclusion logic

Begin and End

>> r = 1..10
=> 1..10
>> R.begin
=> 1
>> R.end
=> 10
Exclusive range?

>> r.exclude_end?
=> false
Cover?

If the argument to the method is greater than the start of the range, less than the end point, Range says it cover the object.

>> r = "a" ... " Z
=> "a" ... " Z
>> r.cover? ("a")
=> true
>> r.cover? ("ABC")
=> true
>> r.cover? ("A")
=> false
"A" >= "a"
"A" <= "Z"

"ABC" >= "a"
"abc" <= "Z"

"A" < "a"
Incompatible situations:

>> r.cover? ([])
=> false
Include?

Include? Consider a range as a collection of values.

>> r.include? ("a")
=> true
>> r.include? ("ABC")
=> false
>> r = 1.0..2.0
=> 1.0..2.0
>> r.include? (1.5)
=> true
Set

Use Set First:

Require ' Set '
Set is a collection, and the items inside it are unique. A project can be anything, string, Integer, array, other set, and so on.

Create set

The Set.new constructor creates a set.

>> require (' Set ')
=> false
>> n = [1,2,3]
=> [1, 2, 3]
>> n_set = set.new (n)
=> #<set: {1, 2, 3}>
Provide a code block to the constructor:

>> names = ["David", "Yukihiro", "Amy"]
=> ["David", "Yukihiro", "Amy"]
>> Name_set = set.new (names) {|name| name.upcase}
=> #<set: {"DAVID", "Yukihiro", "AMY"}>
Working with SET elements

>> n = set.new ([1,2])
=> #<set: {1, 2}>
>> N << 3
=> #<set: {1, 2, 3}>
>> N << 3
=> #<set: {1, 2, 3}>
>> N
=> #<set: {1, 2, 3}>
Delete

>> N.delete (2)
=> #<set: {1, 3}>
Add

>> N.add? (2)
=> #<set: {1, 3, 2}>
>> N
=> #<set: {1, 3, 2}>
>> N.add? (2)
=> Nil
Intersection,union,difference

Intersection, alias &
Union, alias + with |
Difference, alias-
All of these methods return the new set.

>> n = set.new ([1, 2, 3])
=> #<set: {1, 2, 3}>
>> n1 = Set.new ([3, 4, 5])
=> #<set: {3, 4, 5}>
>> n-n1
=> #<set: {1, 2}>
>> N + N1
=> #<set: {1, 2, 3, 4, 5}>
>> N & N1
=> #<set: {3}>
>> N | N1
=> #<set: {1, 2, 3, 4, 5}>
^

>> N ^ N1
=> #<set: {4, 5, 1, 2}>
Merge

>> N
=> #<set: {1, 2, 3}>
>> n.object_id
=> 70179526750720
>> N.merge ([4])
=> #<set: {1, 2, 3, 4}>
>> n.object_id
=> 70179526750720
Merge with Hash:

>> N
=> #<set: {1, 2, 3, 4}>
>> N.merge ({"Beijing" => "BJ"})
=> #<set: {1, 2, 3, 4, ["Beijing", "BJ"]}>
Subset and Superset

Subset: Subsets, superset: Superset

>> n = set.new ([1, 2, 3])
=> #<set: {1, 2, 3}>
>> n1 = Set_new ([1, 2])
>> n1.sub Set? (n)
=> true
>> n.superset? ( N1)
=> true
Proper_subset and Proper_superset. The proper subset is at least one item less than the parent, and if two sets are the same, they are subset, but not proper subsets.

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.