Type:
Class

ruby 1.8.x –> use Hash#index

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:

1
grades = { "Jane Doe" => 10, "Jim Doe" => 6 }

Hashes allow an alternate syntax form when your keys are always symbols. Instead of

1
options = { :font_size => 10, :font_family => "Arial" }

You could write it as:

1
options = { font_size: 10, font_family: "Arial" }

Each named key is a symbol you can access in hash:

1
options[:font_size# => 10

A Hash can also be created through its ::new method:

1
2
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. If no default is set nil is used. You can set the default value by sending it as an argument to ::new:

1
grades = Hash.new(0)

Or by using the default= method:

1
2
grades = {"Timmy Doe" => 8}
grades.default = 0

Accessing a value in a Hash requires using its key:

1
puts grades["Jane Doe"] # => 10

Common Uses

Hashes are an easy way to represent data structures, such as

1
2
3
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 brackets are used below. If a hash is the last argument on a method call, no braces are needed, thus creating a really clean interface:

1
2
3
4
5
6
Person.create(name: "John Doe", age: 27)
 
def self.create(params)
  @name = params[:name]
  @age  = params[:age]
end

Hash Keys

Two objects refer to the same hash key when their hash value is identical and the two objects are eql? to each other.

A user-defined class may be used as a hash key if the hash and eql? methods are overridden to provide meaningful behavior. By default, separate instances refer to separate hash keys.

A typical implementation of hash is based on the object's data while eql? is usually aliased to the overridden == method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Book
  attr_reader :author, :title
 
  def initialize(author, title)
    @author = author
    @title = title
  end
 
  def ==(other)
    self.class === other and
      other.author == @author and
      other.title == @title
  end
 
  alias eql? ==
 
  def hash
    @author.hash ^ @title.hash # XOR
  end
end
 
book1 = Book.new 'matz', 'Ruby in a Nutshell'
book2 = Book.new 'matz', 'Ruby in a Nutshell'
 
reviews = {}
 
reviews[book1] = 'Great reference!'
reviews[book2] = 'Nice and compact!'
 
reviews.length #=> 1

See also Object#hash and Object#eql?

[] 2
  • References/Ruby on Rails/Ruby/Classes/Hash

hsh[key] â value Instance Public methods Element ReferenceâRetrieves the

2025-01-10 15:47:30
length
  • References/Ruby on Rails/Ruby/Classes/Hash

hsh.length â fixnum Instance Public methods Returns the number of key-value

2025-01-10 15:47:30
each_value
  • References/Ruby on Rails/Ruby/Classes/Hash

hsh.each_value {| value | block } â hshhsh.each_value â an_enumerator Instance Public methods

2025-01-10 15:47:30
initialize_copy
  • References/Ruby on Rails/Ruby/Classes/Hash

initialize_copy(p1) Instance Public methods

2025-01-10 15:47:30
eql?
  • References/Ruby on Rails/Ruby/Classes/Hash

hash.eql?(other) â true or false Instance Public methods Returns true

2025-01-10 15:47:30
hash
  • References/Ruby on Rails/Ruby/Classes/Hash

hsh.hash â fixnum Instance Public methods Compute a hash-code for this hash

2025-01-10 15:47:30
select
  • References/Ruby on Rails/Ruby/Classes/Hash

hsh.select {|key, value| block} â a_hashhsh.select â an_enumerator Instance Public

2025-01-10 15:47:30
pretty_print
  • References/Ruby on Rails/Ruby/Classes/Hash

pretty_print(q) Instance Public methods

2025-01-10 15:47:30
fetch
  • References/Ruby on Rails/Ruby/Classes/Hash

hsh.fetch(key [, default] ) â objhsh.fetch(key) {| key | block } â obj Instance Public methods

2025-01-10 15:47:30
delete
  • References/Ruby on Rails/Ruby/Classes/Hash

hsh.delete(key) â valuehsh.delete(key) {| key | block } â value Instance Public methods

2025-01-10 15:47:30