Ruby Code Snippets


Table Of Contents

External Resources / Tutorials

If/Then/Else/Elsif

if name == "John"
  puts "Hi There John!"
elsif name == "Bob"
  puts "Heyo Bob!"
else 
  puts "I don't know you! Stranger Danger!!"
end
					

If/Then/Else/Elsif Multiple Conditionals

Or...
if name == "John" || name == "Bob"
  puts "Hi There John or Bob!"
end
					


And...
if number > 41 && number < 100
  puts "Your number is between 41 and 100!"
end
					

While Loops

num = 0
while num < 10 do
  puts num += 1
end
					

Until Loops

num = 0
until num == 10 do
  puts num += 1
end
					

For Loops

for num in 0..5
  puts num
end
					

Each Loops

(0..5).each do |num|
  puts num
end
					


Each on an Array...
our_array = [0,1,2,3,4,5]
our_array.each do |num|
  puts "This number is #{our_array[num]}"
end
					

Each Loop With Index

# Create An Array
our_array = ["John", "Jane", "Bill", "Mary", "Fred"]

# Each Loop through the array WITH and index
our_array.each_with_index do | name, index |
	puts "#{index + 1}. Hello, my name is #{name}"  # add 1 to index just so it doesn't start with 0
end
					

Arrays

names = ["John", "Mary", "Tim", "Beatrice", "Bluto"]
puts names[2]
					


Multidementional Arrays
names = ["John", "Mary", "Tim", "Beatrice", "Bluto", [1,2,3,4,5]]
puts names[5][3]
					

Double Arrays

# Use double arrays to create a grid for a word search puzzle

box = []

10.times do | row |
  box[row] = []
  10.times do
    box[row] << "*"
  end
end

box.each do | row |
  # add spaces between our output
  puts row.join( ' ' )
end
					

Hashes

favorite_pizza = {
  "John" => "Pepperoni",
  "Tim" => "Mushroom",
  "Mary" => "Cheese",
  "Beatrice" => "Ham and Onion",
  "Bluto" => "Supreme"
}
puts favorite_pizza["John"]
					

Methods

def is_even(x)
  if x % 2 == 0
    return true
  else
    return false
  end
end

is_even(99)
					


Methods With More Than One Argument...
def namer(first, last)
  puts "First Name: #{first}"
  puts "Last Name: #{last}"
end

namer("John", "Elder")
					

Change Ruby's + Method

# Modify the + method in our class
class Adder
  def initialize(a)
    @a = a
    
  end
  
  def number
    @number = @a
  end
  
  def +(other)
    return (self.number + other.number) * 2
  end
end


# Instantiate and pass in two numbers
add = Adder.new(1)
add2 = Adder.new(4)


# Add the two numbers
puts add + add2
# Should output 10 not 5 because we multiplied by 2
					

Classes

# Classes Start With Capital Letters
class Product
  # Always Initialize It First
  def initialize( description, price)
    # generate a random number for the ID just for fun
    @id = rand(100...999)
    	
    # suck in our description and price from the outside
    @description = description
    @price = price
    	
  end
    
  def to_s
    # return by rewriting to_s :-p and add tabs with \t
    return "#{@id}\t#{@description}\t#{@price}"
  end
end

# Instantiate our class
book = Product.new( "Ruby On Rails For Web Development", 26.95 )
book2 = Product.new( "Intro To Ruby", 25.95 )

# Call the thing!
puts book
puts book2
					

Wildcard Class Initialization (splat argument)

# Classes Start With Capital Letters
class Product
  # Always Initialize It First push wildcards into the initialization with *placeholder
  def initialize( *placeholder_args )
    #suck in whatever you passed during initialization into a @whatever array
    @whatever = placeholder_args
  end

  def do_something
  	@do_something = @whatever
  end
end

# Set it up... Instantiate our class
book = Product.new( "a thing", "another thing", 3, 4, "last thing")


# Call the thing! 
puts book.inspect

# Print out the 3rd item in the array
puts book.do_something[2]

					

Class Getters and Setters and attr_accessor

# Getters 'get' stuff from your class
# Setters 'set' stuff in your class
class Product
  # Always Initialize It First
  def initialize( description, price)
    @id = rand(100...999)
    @description = description
    @price = price
  end

  # Create GETTER for our descrition
  def description
  	# don't need "return", but I like it
    return @description
  end

  # Create SETTER for our description...Setters use = and can be named after its getter
  def description=( description )
    @description = description
  end


  def to_s
    # return by rewriting to_s :-p and add tabs with \t
    return "#{@id}\t#{@description}\t#{@price}"
  end
end
 
# Set it up... Instantiate our class
book = Product.new( "Ruby On Rails For Web Development", 26.95 )
book2 = Product.new( "Intro To Ruby", 25.95 )
 
# Call the thing!
puts book
puts book2

# Call The Description Getter
puts book.description
# Call the Setter, set a different Description
puts book.description= "I Like Cheese!"
					


Ruby will Write Your Getter, Setter, and Instance Variables If You use attr_accessor
# Delete the Getter and Setter from above, replace it with attr_accessor
# Note: Doesn't write your initialize method instance variables!
class Product
  attr_accessor :description


  # Always Initialize It First
  def initialize( description, price)
    @id = rand(100...999)
    @description = description
    @price = price
  end

  
  def to_s
    # return by rewriting to_s :-p and add tabs with \t
    return "#{@id}\t#{@description}\t#{@price}"
  end
end
 
# Set it up... Instantiate our class
book = Product.new( "Ruby On Rails For Web Development", 26.95 )
book2 = Product.new( "Intro To Ruby", 25.95 )
 
# Call the thing!
puts book
puts book2

# Call The Description Getter
puts book.description
# Call the Setter, set a different Description
puts book.description= "I Like Cheese!"
					

Class Inheritance

# Our Lion Class Inherits All the stuff from our Animal Class
class Animal
  attr_accessor :color, :name
  def initialize ( name, color )
    @name = name
    @color = color
  end
end

class Lion < Animal		# Inherit by using < Animal 
  def speak
    return "RAWR!"
  end
end

#  Instantiate our class
lion = Lion.new( "lion", "golden" )

# Inspect
puts lion.inspect

# Speak
puts lion.speak

# Color inherited from Animal class!
puts lion.color
					

Open a File, Read Through It

# open a file (in current directory), stuff it into a variable
my_file = File.open("whatever.txt")

# loop through the file = while not at end of file
while ! my_file.eof?
	stuff = my_file.gets.chomp
	# print out each line
	puts stuff
end

# close the file
my_file.close
					

Open a File, Read Through It, Stick Items In An Array

# open a file (in current directory), stuff it into a variable
my_file = File.open("whatever.txt")

my_array = []
# loop through the file = while not at end of file
while ! my_file.eof?
	stuff = my_file.gets.chomp
	# Stick the stuff into the array
	my_array << stuff
end

# close the file
my_file.close
					

Open File Modes

#######################################################################
#
# Ruby File Open Modes:
#
# r (read only default)
#
# r+ (Read-write starting at beginning of file)
# 
# w (Write-only, creates new file for writing)
# 
# w+ (Read-write, truncates or creates new file for read and write)
# 
# a (Write-only, starts at end of file if exists, or creates new one)
# 
# a+ (Read-write, starts at end of file if exists, or creates new one)
# 
# b (Dos/Windows binary file mode)
# 
#######################################################################


# Open File For Write Only
my_file = File.open("whatever.txt", "w")

# Open File For Read-Write Beginning of file
my_file = File.open("whatever.txt", "r+")

# Open File For Read-Write Truncates
my_file = File.open("whatever.txt", "w+")

# Open File For Write-Only
my_file = File.open("whatever.txt", "a")

# Open File For Read-Write end of file
my_file = File.open("whatever.txt", "a+")


# close the file
my_file.close
					

Clear The Screen

system "clear"
					

Loop Through a Menu Method

def menu ()
    menu_string = "1. Show Menu\n"
    menu_string += "2. Add Numbers\n"
    menu_string += "3. Subtract Numbers\n"
    menu_string += "4. Quit\n"
    return menu_string
end


# Main Program Starts

system "clear"  # Clear the screen
choice = 0

while choice < 4 do     
    puts menu()
    choice = gets.to_i
    
    if choice == 1
        system "clear"
    elsif choice == 2
        puts "\n\nAdd Some Numbers\n\n"
    elsif choice == 3
        puts "\n\nSubtract some Numbers\n\n"
    else
    end
end
					

Grab The Sourcecode of a Remote Website

require "open-uri"
puts open("http://johnelder.org/").read
					

Output Files In A Directory

First Create an Instance Variable In Your Rails Controller

@files = Dir.glob('*')
					


Next Add This To Your Rails View

<ul>
  <% for file in @files %>
    <li>
      File name is: <%= file %>
    </li>
  <% end %>
</ul>
					

Find Longitude and Latitude Using Google's Geocoding API

First Add Gemfiles To Your Ruby Installation Via The Command Line

gem install "rest-client"
gem install "crack"
					


Then Add This Code

require 'rubygems'
require 'rest-client'
require 'crack'

def get_coordinates_from_address(addr)
   base_google_url = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address="
   res = RestClient.get(URI.encode("#{base_google_url}#{addr}"))
   parsed_res = Crack::XML.parse(res)
   lat = parsed_res["GeocodeResponse"]["result"]["geometry"]["location"]["lat"]
   lng = parsed_res["GeocodeResponse"]["result"]["geometry"]["location"]["lng"]
   
   return "#{lat}, #{lng}"
end

#Get the address from the user
puts "Enter and Address"
addy = gets.chomp

#run this sucker!
latlng = get_coordinates_from_address(addy)
puts latlng