DEV Community

salcasta
salcasta

Posted on

Ruby Basics - Arrays & Intro to Hashes

An array is an object that can hold multiple items (pieces of info, including other arrays).

To access the array use its index starting from 0 (use -1 to get the last item).

array | 5 | 7 | 9 | 2 | 0 |

index 0 1 2 3 4

A hash is an object similar to an array, but a hash as both a key and a value.

When creating a hash, use Hash.new and then add to it by using the hash name next to brackets with the key equal to the value.

pets = Hash.new

pets['Cash'] = 'cat'

puts pets['Cash']
Enter fullscreen mode Exit fullscreen mode

To iterate over a hash, it is the same as an array except add a second parameter to get the value of the key

lunch_order = {
  "Ryan" => "wonton soup",
  "Eric" => "hamburger",
  "Jimmy" => "sandwich",
  "Sasha" => "salad",
  "Cole" => "taco"
}

lunch_order.each { |x, y| puts y }


Output:
wonton soup
hamburger
sandwich
salad
taco
Enter fullscreen mode Exit fullscreen mode

Mini Project

Creating a program that will analyze how many words are used in a block of text and the frequency.

puts = 'Analyze this phrase'
text = gets.chomp

words = text.split

frequencies = Hash.new(0)

words.each { |word| frequencies[word] += 1}

frequencies = frequencies.sort_by do |word, count|
  count
end
frequencies.reverse!

frequencies.each do |word, count|
  puts "#{word} #{count.to_s}"
end

 He walked down the steps from the train station in a bit of a hurry knowing the secrets in the briefcase must be secured as quickly as possible. Bounding down the steps, he heard something behind him and quickly turned in a panic. There was nobody there but a pair of old worn-out shoes were placed neatly on the steps he had just come down. Had he past them without seeing them? It didn't seem possible. He was about to turn and be on his way when a deep chill filled his body.Then came the night of the first falling star. It was seen early in the morning, rushing over Winchester eastward, a line of flame high in the atmosphere. Hundreds must have seen it and taken it for an ordinary falling star. It seemed that it fell to earth about one hundred miles east of him.

the 6
a 5
he 3
in 3
his 2
on 2
was 2
and 2
possible. 2
quickly 2
as 2
be 2
of 2
steps 2
down 2
He 2
body. 1
filled 1
chill 1
deep 1
when 1
way 1
turn 1
to 1
about 1
seem 1
didn't 1
It 1
them? 1
seeing 1
without 1
them 1
past 1
Had 1
down. 1
come 1
just 1
had 1
neatly 1
placed 1
were 1
shoes 1
worn-out 1
old 1
pair 1
but 1
there 1
nobody 1
There 1
panic. 1
turned 1
him 1
behind 1
something 1
heard 1
steps, 1
Bounding 1
secured 1
must 1
briefcase 1
secrets 1
knowing 1
hurry 1
bit 1
station 1
train 1
from 1
walked 1

Enter fullscreen mode Exit fullscreen mode

Top comments (0)