ruby – basic data structures, array, list, and hash

Arrays

Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array — that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

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

names = Array.new
names = Array.new(20) # Set the size of an array

puts names.size # 20
puts names.length #20

#----------------

names = Array.new(4, "mac")
puts "#{names}" # macmacmacmac

#----------------

nums = Array.new(10) {|e| e = e * 2}
puts "#{nums}" # 024681012141618

nums = Array.new(10) {|e| e = e + 1}
puts "#{nums}" # 12345678910

#----------------

nums = Array.[](1,2,3,4,5)
puts "#{nums}" # 12345

nums = Array[1,2,3,4,5]
puts "#{nums}" # 12345

The Kernel module available in core Ruby has an Array method, which only accepts a single argument. Here, the method takes a range as an argument to create an array of digits:

1
2
digits = Array(0..3)
puts "#{digits}" # 0123

Array built-in methods

Following is the way to create an instance of Array object:

1
2
3
4
Array.[](...) 
Array[...]
[...]
Array(...)

List

1
%w(foo bar)

is a shortcut for

1
["foo", "bar"].

%w quotes like single quotes '' (no variable interpolation, fewer escape sequences), while %W quotes like double quotes "".

1
2
3
irb > foo="hello"             # "hello"
irb > %W(foo bar baz #{foo}) # ["foo", "bar", "baz", "hello"]
irb > %w(foo bar baz #{foo}) # ["foo", "bar", "baz", "#{foo}"]

Hash

A Hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

The order in which you traverse a hash by either key or value may seem arbitrary and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil.

Creating Hashes

Create an empty hash with the new class method:

1
months = Hash.new

You can also use new to create a hash with a default value, which is otherwise just nil:

1
2
months = Hash.new( "month" )
months = Hash.new "month"
1
2
3
4
5
6
7
months = Hash.new( "month" )

puts "#{months[0]}"
puts "#{months[72]}"

# month
# month
1
2
3
4
5
6
7
H = Hash["a" => 100, "b" => 200]

puts "#{H['a']}"
puts "#{H['b']}"

# 100
# 200

You can use any Ruby object as a key or value, even an array, so following example is a valid one:

1
[1,"jan"] => "January"

Hash Built-in Methods

1
2
3
4
Hash[[key =>|, value]* ]
Hash.new
Hash.new(obj)
Hash.new { |hash, key| block }
1
2
3
4
5
months = Hash.new( "month" )
months = {"1" => "January", "2" => "February"}
keys = months.keys

puts "#{keys}" # ["1", "2"]