Monday, March 19, 2007

Collection, Container, in Ruby

In programming generally, you deal not only with individual objects but with collections of objects. 这就是为什么会有collection这个词汇的原因。:-)

Ruby represents collections of objects by putting them inside container objects. In Ruby, two built-in classes dominate the container-object landscape: Array and Hash.

A built-in Ruby module called Enumerable, which encapsulates a great deal of the functionality of arrays and hashes.

An array is an ordered collection of objects, ordered meaning that you can select objects from the collection based on a consistent numerical index.

Hashes are unordered collections, they store objects in pairs, each pair consisting of a key and a value. You retrieve a value by means of the key.

The Rails framework, too, makes heavy use of hashes. A large number of the most common methods used in writing Rails applications take hashes as their arguments.

Array

To create an Array: Rails 通常使用a = []这种方式,而不使用a = Array.new的方式。

To insert an element into the array, you do this:
a = []
a[0] = "something"

To add an object to the beginning of an array, you can use unshift:
a.unshift("something")

To add an object to the end of an array, you use push:
a = [1,2,3,4]
a.push(5)
a.putsh(6, 7, 8)

或者使用a << 5,不过这种方式一次只能加一个value。

Corresponding to unshift and push are their opposite numbers, shift and pop.

To add the contents of array b to array a, you can use concat:
$ [1,2,3].concat([4,5,6])
$ => [1, 2, 3, 4, 5, 6]

To combine two arrays into a third, new array, you can do so with the + method:
$ a = [1, 2, 3]
$ b = [4, 5, 6]
$ put c = a + b
$ => [1, 2, 3, 4, 5, 6]

To replace the contents of one array with the contents of another, use replace:
$ a = [1,2,3]
$ a.replace([4,5,6])

a.each

a.find

a.

Hash

To create a hash:
h = {}
for example:
state_hash = { "Connecticut" => "CT","Delaware" => "DE","New Jersey" => "NJ","Virginia" => "VA" }

The => operator connects a key onthe left with the value corresponding to it on the right.

To add a key/value pair to a hash, you use essentially the same technique as foradding an item to an array: the []= method :
state_hash["New York"] = "NY"

To iterate over a hash several ways. Like arrays, hashes have a basic each method. On each iteration, an entire key/value pair is yielded to the block, in the form of a two-element array:
$ h = {1 => "one", 2 => "two" }
$ h.each do key, value
      puts "The word for #{key} is #{value}."
end

dfd

No comments: