Ruby Arrays And Hashes


Collapse Content

Arrays

Arrays are ordered, integer-indexed collections of any object.


# This is an array
array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]

# Arrays can contain different types of items    
[1, "hello", false] #=> [1, "hello", false]

# Arrays can be indexed
# From the front
array[0] #=> 1
array[12] #=> nil

# From the end
array[-1] #=> 5

# With a start index and length
array[2, 3] #=> [3, 4, 5]

# Or with a range
array[1..3] #=> [2, 3, 4]

# Like arithmetic, [var] access is just syntactic sugar
# for calling a method [] on an object
array.[] 0 #=> 1
array.[] 12 #=> nil

# Add to an array with <<
array << 6 #=> [1, 2, 3, 4, 5, 6]

#Lots of methods for getting info about an Array
array.length #=> 6
array.first #=> 1
array.last #=> 6

array.include?(3) #=> true
array.include?(9) #=> false

Hashes

A Hash is a dictionary-like collection of unique keys and their values.


# Hashes are denoted with curly braces:
hash = {'color' => 'green', 'number' => 5}

hash.keys #=> ['color', 'number']
hash.values #=> ['green', 5]

# Hashes can be quickly looked up by key:
hash['color'] #=> 'green'
hash['number'] #=> 5

# Asking a hash for a key that doesn't exist returns nil:
hash['missing'] #=> nil

# Since Ruby 1.9, there's a special syntax when using symbols as keys:

new_hash = { defcon: 3, action: true}    
new_hash.keys #=> [:defcon, :action]

Tip: Both Arrays and Hashes are Enumerable. They share a lot of useful methods such as each, map, count, and more

Challenge

What will the following code return?

array = [1, 2, 3, 4, 5]
array[1..2]

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

You will be given an array of numbers ar. Create and print another array of length 2 that just contains the first and last number in the original array.

(Note: To print an array ar, just use print ar. To print a newline, use "\n".)

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]