From d54d88b50044beb433e6a4ae19236e163581ac91 Mon Sep 17 00:00:00 2001 From: Alvaro Pereyra Date: Mon, 3 Oct 2011 22:51:40 -0500 Subject: [PATCH] adding documentation for Hash --- hash.c | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 files changed, 63 insertions(+), 5 deletions(-) diff --git a/hash.c b/hash.c index a6096f0..ee126d9 100644 --- a/hash.c +++ b/hash.c @@ -3150,14 +3150,72 @@ env_update(VALUE env, VALUE hash) } /* - * A Hash is a collection of key-value pairs. It is - * similar to an Array, except that indexing is done via - * arbitrary keys of any object type, not an integer index. Hashes enumerate - * their values in the order that the corresponding keys were inserted. + * A Hash is a dictionary-like collection of unique keys and + * their values. Also called associative arrays, they are similar to + * Arrays, but where an Array uses integers + * as its index, a Hash allows you to use any object type. + * + * Hashes enumerate their values in the order that + * the corresponding keys were inserted. + * + * A Hash can be easily created by using its implicit form: + * + * grades = {"Jane Doe" => 10, "Jim Doe" => 6} + * + * Hashes allow an alternate syntax form when your keys are always symbols. + * Instead of + * + * options = {:font_size => 10, :font_family => "Arial"} + * + * You could write it as: + * + * options = {font_size: 10, font_family: "Arial"} + * + * Each named key is a symbol you can access in hash: + * + * options[:font_size] #=> 10 + * + * A Hash can also be created through its new method: + * + * grades = Hash.new + * grades["Dorothy Doe"] = 9 * * Hashes have a default value that is returned when accessing * keys that do not exist in the hash. By default, that value is - * nil. + * nil. You can setup its default value by sending it as + * an argument on the Hash initialization: + * + * grades = Hash.new(0) + * + * Or by using its default method: + * + * grades = {"Timmy Doe" => 8} + * grades.default = 0 + * + * Accessing a Hash requires using its key: + * + * puts grades["Jane Doe"] #=> 10 + * + * === Common Uses + * + * Hashes are an easy way to represent data structures, such as + * + * books = {} + * books[:matz] = "The Ruby Language" + * books[:black] = "The Well-Grounded Rubyist" + * + * Hashes are also commonly used as a way to have named parameters + * in functions. Note that no brackes are used below. If a hash is + * the last argument on a method call, no braces are needed, + * thus creating a really clean interface: + * + * Person.create(name: "John Doe", age: 27) + * + * def self.create(params) + * @name = params[:name] + * @age = params[:age] + * end + * * */ -- 1.7.4.4