Skip to content

Instantly share code, notes, and snippets.

@mkoby
mkoby / call_employee.rb
Created June 19, 2012 18:40
Intro to Ruby - 15 - Separating Programs into Multiple Files
require ‘./employee.rb’
e = Employee.new
e.say_hello(“Michael”)
@mkoby
mkoby / error_handling.rb
Created May 24, 2012 21:24
Intro to Ruby - 14 - Error Handling
2/0 # => ZeroDivisionError
# In order to give the user a better error message than "ZeroDivisionError"
# we have to wrap the code using begin & rescue keywords so that Ruby knows
# that we specifically want to do something if an error is encountered
begin
2/0
rescue
“You can’t divide by ZERO!”
@mkoby
mkoby / 01_reading_file.rb
Created May 24, 2012 21:14
Intro to Ruby - 13 - Files
def get_result(number)
if(number % 3 == 0 && number % 5 == 0)
return "FizzBuzz"
elsif(number % 3 == 0)
return "Fizz"
elsif(number % 5 == 0)
return "Buzz"
else
return number.to_s
end
@mkoby
mkoby / 01_hello.rb
Created April 16, 2012 20:52
Intro to Ruby - 12 - Input, Output
puts “Enter your name:”
name = gets.chomp
puts “Hello, #{name}!”
## Output
# PROMPT> ruby hello.rb
# Enter your name:
# Michael
# Hello, Michael!
@mkoby
mkoby / using_modules.rb
Created April 9, 2012 17:11
Intro to Ruby - 11 - Modules
# Basic Module
module MyModule
def module_hello
return “MyModule module_hello method”
end
end
# Class with module included
class ClassOne
include MyModule
@mkoby
mkoby / 001_Employee.rb
Created April 9, 2012 16:56
Intro to Ruby - 10 - Classes: Putting it All Together
class Employee
attr_accessor :name, :age
attr_reader :salary, :department
initialize(name = “”, salary = 0, department = “”)
@name = name
@salary = salary
@department = department
end
def set_new_salary(salary)
@salary = salary
@mkoby
mkoby / 001_class_methods.rb
Created April 9, 2012 16:36
Intro to Ruby - 09 - Methods in Classes
class Employee
attr_accessor :name
def self.new_with_name(name)
output = self.new
output.name = name
return output
end
end
# List all methods on the employee class and sort them
@mkoby
mkoby / initialize_methods.rb
Created March 30, 2012 20:34
Intro to Ruby - 08 - Classes: Part 02
## Here is a basic class, with a basic
## initialize method that takes a name
## argument
class Employee
attr_accessor :name
def initialize(name)
@name = name
end
end
@mkoby
mkoby / 001_basic_class.rb
Created March 30, 2012 20:19
Intro to Ruby - 07 - Classes: Part 01
## This is a basic Ruby class
class Employee
end
## We can create an object from this class
e = Employee.new # => #<Employe:0x37978873> #Or some other gibberish
@mkoby
mkoby / 001_multiple_arguments.rb
Created March 30, 2012 20:06
Intro to Ruby - 06 - Methods Addendum
## Basic method with multiple arguments
def add_numbers(a, b)
a + b
end
add_numbers(5, 4) # => 9