The Ruby collection Guide (1): array

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
A sorting and searching a lot of programming. In comparison to the old C language, you may want to write their own data structure and algorithm to accomplish these tasks. However, in Ruby in order to focus more on the task processing has the structure for the abstract way.
Following these guidelines will introduce these abstract structure. These guidelines may not be comprehensive - light Ruby set to write a book. - but I can cast a wide net, and I covered I think as a Ruby programmer will often have to calculate the aspect. They can be divided into 4 aspects:
The array and hash, collection and arrangement of enumeration and counter tips and hints to the guiding example very much. I feel that learning the best way is to open the IRB command line follow the example of learning by yourself, be the most changeful ways to create program.

Array

The array is the Ruby collection in a horse. Many methods of operation in the set of return value is an array, even if the original collection is not an array. In fact, they are not true array, it is a universal data structure. You can use them to do set, stack, or a queue. The function of Python and list.like.

Establish

Create an array of Ruby and some dynamic language to create modelike.
>> numbers = [1, 0, 7]
>> numbers[2]
=> 7
>> numbers.size
=> 3
In the type array doesn't have to be the same. They are diverse

>> data = ["bob", 3, 0.931, true]

Because the Ruby is entirely based on object, the array will be described as an object and not just the special translation rules. This means you can like other objects to construct arrays.

>> numbers = Array.new([1,2,3]) 
=> [1, 2, 3]

Array constructor can pass a size of the beginning, but it may not work with your imagination. Because the Ruby array is dynamic, need not apply enough space in advance. When you come into a digital Array.new way, one will contain the nil object will be created.

>> numbers = Array.new(3)
=> [nil, nil, nil]
Although nil is an independent object, it is also in the collection and other objects occupy position. So when you add a nil object to an array, it will add to the end of the array.
>> numbers <<3
=> [nil, nil, nil, 3]
>> numbers.size
=> 4

If you pass the second parameters in Array.new, the array will use it instead of nil to initialize.

>> Array.new(3, 0)
=> [0, 0, 0] 

>> Array.new(3, :DEFAULT)
=> [:DEFAULT, :DEFAULT, :DEFAULT]

The increase of standard text, Ruby offers some other by% to achieve syntax shortcuts. Symbol.

>> ORD = "ord"
>> %W{This is an interpolated array of w#{ORD}s}
=> ["This", "is", "an", "interpolated", "array", "of", "words"] 

>> %w{This is a non-interpolated array of w#{ORD}s}
=> ["This", "is", "a", "non-interpolated", "array", "of", "w\#{ORD}s"]

Array of directory

Many languages if you attempt to access an array index is not exist will throw an exception. If you try to read a nonexistent index, Ruby returns nil.
>> spanish_days = []
>> spanish_days[3]
=> nil

If you write a nonexistent index, Ruby will write a nil in the index position.

>> spanish_days[3] = "jueves"  
=> [nil, nil, nil, "jueves"] 
>> spanish_days[6] = "domingo" 
=> [nil, nil, nil, "jueves", nil, nil, "domingo"]

In many languages, if you visit a negative index will cause an error. But Ruby said the negative index is the beginning of the end of the array, reverse increased.

>> ["a","b","c"][-1]
=> "c"
>> ["a","b","c"][-3]
=> "a"

If you provide a does not exist, the negative array index, the result is that there is no -nil

>> ["a","b","c"][-4]
=> nil

Array classification

Another useful feature in the Ruby array that can classify elements. However, in Ruby you can specify classification of elements with more demanding and many different ways.

>> letters = %w{a b c d e f}
=> ["a", "b", "c", "d", "e", "f"]
>> letters[0..1]
=> ["a", "b"]
>> letters[0, 2]
=> ["a", "b"]
>> letters[0...2]
=> ["a", "b"]
>> letters[0..-5]
=> ["a", "b"]
>> letters[-6, 2]
=> ["a", "b"]

Here is the example introduction
letters[0..1] – Returns the element to 1 from 0
letters[0, 2] – Return from the 2 elements in 0 position after the start of the letters[0... 2] – returns from 0 until 2 elements letters[0..-5] – returned from the 0 to the last position of 5 elements letters[-6, 2] – returned from the last sixth to 2 elements if you just started learning Ruby, you might want to know how this is achieved. The best way to access an array is [] method.
>> letters.[](0..1)
=> ["a", "b"]

In addition, 0..1 is just a fake Range object. You can use the class method to verify.

>> (0..1).class
=> Range

So in fact is the Range object is passed to the Array[] target classification.

>> letters.[](Range.new(0,1))
=> ["a", "b"]

If you like, the Ruby based on the object-oriented way to create beautiful things. So if you want to use numbers to take English character.?
Numerouno gem can resolve English digital.

$ gem install numerouno

>> require 'numerouno'
>> "one-hundred sixty three".as_number
=> 163

With numerouno you can make an array class has English index.

class EnglishArray <Array
  def [](idx)     
    if String === idx
      self.at(idx.as_number)  
    end
  end
end 

>> arr = EnglishArray.new(["a","b","c"])
>> arr["one"]
=> "b"

Deformation

Remember I said before Ruby Array type is a universal structure? Here is you can use on the Array example.
Adding elements
>> [1,2,3] <<"a" 
=> [1,2,3,"a"]

>> [1,2,3].push("a")
=> [1,2,3,"a"]

>> [1,2,3].unshift("a")
=> ["a",1,2,3]

>> [1,2,3] <<[4,5,6]
=> [1,2,3,[4,5,6]]

Remove elements

>> arr = [1,2,3]
>> arr.pop
=> 3
>> arr
=> [1,2]

>> arr = ["a",1,2,3]
>> arr.shift
=> "a"
>> arr
=> [1,2,3]

>> arr = [:a, :b, :c]
>> arr.delete(:b)
=> :b
>> arr
=> [:a, :c]
>> arr.delete_at(1)
=> :c
>> arr
=> [:a]

Adds an array of

>> [1,2,3] + [4,5,6]
=> [1,2,3,4,5,6]

>> [1,2,3].concat([4,5,6])
=> [1,2,3,4,5,6]

>> ["a",1,2,3,"b"] - [2,"a","b"]
=> [1,3]

Boolean operation

>> [1,2,3] & [2,3,4]
=> [2,3]

>> [1,2,3] | [2,3,4]
=> [1,2,3,4]

>> arr1 = [1,2,3]
>> arr2 = [2,3,4]
>> xor = arr1 + arr2 - (arr1 & arr2)
=> [1,4]
Mobile elements

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

>> [1,2,3].rotate
=> [2,3,1]

>> [1,2,3].rotate(-1)
=> [3,1,2]
Safety tips

>> arr = [1,2,3]
>> arr.freeze
>> arr <<4  
=> RuntimeError: can't modify frozen Array

Adding elements to a String

>> words = ["every","good","boy","does","fine"]
>> words.join
=> "everygoodboydoesfine"

>> words.join(" ")
=> "every good boy does fine"

Delete from

>> [1,[2,3],[4,["a", nil]]].flatten
=> [1,2,3,4,"a",nil]

>> [1,[2,3],[4,["a", nil]]].flatten(1)
=> [1,2,3,4,["a", nil]]
Delete replica

>> [4,1,2,1,5,4].uniq
=> [4,1,2,5]
Cutting

>> arr = [1,2,3,4,5]
>> arr.first(3)
=> [1,2,3]

>> arr.last(3)
=> [3,4,5]

Query

>> ["a","b","c"].include? "d"
=> false

>> ["a", "a", "b"].count "a"
=> 2

>> ["a", "a", "b"].count "b"
=> 1

>> [1,2,[3,4]].size
=> 3


Iteration

Iteration can be said to be Ruby true highlight. In many languages iterative feeling is very clumsy. However, in Ruby you don't feel you need to write a typical for cycle.
The core of the constructor in Ruby is the each iterative method.
>> ["first", "middle", "last"].each { |i| puts i.capitalize }
First
Middle
Last

Although each is the core of Ruby iteration, but there are many other way. For example, you can pass a reverse_each to reverse iteration set.

>> ["first", "middle", "last"].reverse_each { |i| puts i.upcase }
LAST
MIDDLE
FIRST

Another method is to solve each_with_index can pass a current processing index in the second parameter.

>> ["a", "b", "c"].each_with_index do |letter, index| 
>>   puts "#{letter.upcase}: #{index}"
>> end
A: 0
B: 1
C: 2

The each method is how to work? The best way to understand this is to create your own each.

class Colors
  def each
    yield "red"
    yield "green"
    yield "blue"
  end
end

>> c = Colors.new
>> c.each { |i| puts i }
red
green
blue
Call the yieId method to the each data transmission block. The Ruby for beginners focus here may have some difficulty. It is believed that yieId is called an anonymous body of code, and then you inside the yieId provides a method of. In the previous example, yieId is called 3 times, so the " {|i| puts i}" executed 3 times.


Local iteration

A good thing is circular in start and end points can be specified. The each method can iterate the entire collection.
If you only want to iterative set a part, at least two methods as follows to achieve:
The collection will set cut and cut after iteration




>> [1,2,3,4,5][0..2].each { |i| puts i }
1
2
3

Using Range to generate the index

>> arr = [1,2,3,4,5]
>> (0..2).each { |i| puts arr[i] }
1
2
3

Although compared to open up the ugly, I bet when array element number is large and it takes a long time to copy the second way more effective.

#Each and#map/#collect

In addition to #each, you may encounter #map. The #map class like on #each, but it is to generate arrays in each block call results. This is useful, because #each returns only the call to each which array.



>> [1,2,3].each { |i| i + 1 }
=> [1,2,3]

>> [1,2,3].map { |i| i + 1 }
=> [2,3,4]

If you just for each element to invoke the same method, fast or you can use convenient:

>> [1,2,3].map(&:to_f)
=> [1.0, 2.0, 3.0]

This is equivalent to:

>> [1,2,3].map { |i| i.to_f }
=> [1.0, 2.0, 3.0]

Note: #map does not change the original array value. It simply returns the array generated based on each block call results. If you want to reflect this change in the original array, use the#map!.

>> numbers = [1,2,3]
>> numbers.map(&:to_f)
=> [1.0, 2.0, 3.0]
>> numbers
=> [1, 2, 3]
>> numbers.map!(&:to_f)
=> [1.0, 2.0, 3.0]
>> numbers
=> [1.0, 2.0, 3.0]

You may also notice that the Ruby code in the #collect. It is the same with #map, so that they two are interchangeable.

>> letters = ["a", "b", "c"]
>> letters.map(&:capitalize)
=> ["A", "B", "C"]
>> letters.collect(&:capitalize)
=> ["A", "B", "C"]

The traditional iterative

Ruby provides the traditional " for" iteration. Although the wind look sharper, but also for those from other languages around the novice to collect more familiar, but the wind does not conform to the language habits, because it is not object-oriented, also do not accept block parameters.

>> animals = ["cat", "dog", "bird", "chuck testa"]
>> for animal in animals
>>   puts animal.upcase
>> end
CAT
DOG
BIRD
CHUCK TESTA
If "does not conform to the language habits" is not enough to stop you, can have a look below the display by Nikals B. in the stackoverflow on the abnormal results:

>> results = []
>> (1..3).each { |i| results <<lambda { i } }
>> results.map(&:call)
=> [1, 2, 3]

>> results = []
>> for i in 1..3
>>   results <<lambda { i }
>> end
>> result.map(&:call)
=> [3, 3, 3]

In addition, "for" cycle created" temporary "variable is not temporary. How is the for loop in animals anmial variables, right? No, not right.

>> animal
=> "chuck testa"

Conclusion: Ruby for is most suitable for confusing pearl to stop, or the most suitable for which the meeting care.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Sue at December 09, 2013 - 9:16 AM