Notes on Ruby

language-features ruby
Table of Contents

Symbols

What does it look like?

Starts with a colon, followed by some kind of a name:

`walk(:north)`
`look(:east)`

What is it?

You can think of symbols as special strings that are immutable and are only created once. Its value is equivalent to its name and ruby creates it for you.

When should we use it?

They are very useful when you need to use the same string over and over and you would like its value to be immutable, accessible with speed and use very little memory.

Where should we use it?

Because their values don’t change, they are frequently used as keys in hashes.

Any other weird detail?

Because they are used as keys to hashes very frequently so ruby has a shortcut.

Instead of:

instrument_section = {
:cello => "string",
:clarinet => "woodwind",
}

you can use:

instrument_section = {
cello: "string",
clarinet: "woodwind"
}

Arrays

What is it?

An array is a linear list of objects. You retrieve them via index.

What does it look like?

a = [1, 'cat', 3.14]

When should we use it?

Whenever we would like to store some data together in memory.

Any other weird detail?

Arrays can contain data belonging to different types like in the example shown above.

Hashes

What is it?

A hash is an association, meaning it is a key/value store where each value has an arbitrary key, and you retrieve the value via that key.

What does it look like?

instrument_section = {
"cello" => "string"
"clarinet" => "woodwind"
}

Anything to remember?

  • Keys must be unique.

  • If a key is not found, it returns nil.

  • You can change the default value using instrument_section = Hash.new(0)

Control Structures

What does the if statement look like?

if today.saturday
	puts "Today is saturday"
elsif today.sunday
	puts "Today is sunday"
else
	puts "Go to work"
end

What does the while statement look like?

while weight < 100
	weight++
end

What are statement modifiers?

Statement modifiers are a useful shortcut if the body of an if or while statement is just a single expression.

puts "Danger" if radiation > 3000

square = square * square while square < 1000

Anything weird to remember?

  • nil is a falsy value.

Ruby blocks

What is it?

A code block is a chunk of code you can pass to a method, as if the block were another parameter.

What does it look like?

foo.each { puts "hello"}

foo.each do
	puts "hello"
end

animals = ["ant", "bee", "cat", "dog"]
animals.each { |animal| puts animal }

5.times { print "*" }

3.upto(6) { |i| print i }

("a".."e").each { |char| print char }

("a".."e").each { print _1 }

greet { puts "Hi" }

verbose_greet("Dave", "loyal customer") { puts "Hi"}

How does a method call the block code?

Using the yield statement

def verbose_greet (name, greeting)
	puts "Start method"
	yield(name, greeting)
	puts "End method"
end

verbose_greet("Dave", "hello") { |person, greet| puts "#{person} #{greet}"}

# outputs
# Dave hello

Anything weird to remember?

  • Method parameters appear before the block.

  • You can pass only one block per method call.

  • The yield statement invokes the block.

Classes

What do they look like?

class BookInStock
	def Initialize(isbn, price)
		@isbn = isbn
		@price = Float(price)
	end

	def to_s
		"ISBN: #{@isbn}, price: #{@price}"
	end
end

What is the @ symbol?

It represents the instance variables.

What is to_s?

It is the toString method in ruby.

What is the difference between the puts method and the p method?

The puts method prints the output of to_s method and the p method prints the output of the object.

How do you initialize a class

Using the new keyword. person = Person.new

Naming Conventions

  • local variables, method parameters, and method names start with a lowercase letter or underscore.

  • Global variables start with a $. eg:- $plan, $customer

  • Instance variables start with @. @name, @pw

  • Class variables start with @@ and must be initialized before using it: @@plays, @@count

  • Class name or constants start with an uppercase letter: Person, PI

Input and Output

  • puts - prints a value and makes a new line

  • print - prints a value without a new line

  • gets - used to get input from prompt

  • gets.chomp - removes the carriage return at the end.