Docsity

ruby introduction, Slides of Advanced Computer Programming

Partial preview of the text

Download ruby introduction and more Slides Advanced Computer Programming in PDF only on Docsity!

Ruby on Rails

What's Ruby

A programming language

Developed by Yukihiro

Matsumoto (aka Matz) in the 1990s

Ruby

Syntax

Ruby is largely and loosely

based on perl (hence the name, according to lore)

Completely object oriented

Historical Differences

Javascript--born of the competition between two companies PHP--created by a varied community Ruby--the vision of a single person Rails--the vision of another single person When you compare these, you can see how the starting point influences the process of development

Playing on the Command

Line

Ruby is an interpreter, just like php or bash: Avatar:~ hays$ ruby print "howdy world!" ^d Or, use ruby -e "command": ruby -e 'puts "hello\n"' Or, you can just use irb, which is easier: Avatar:~ hays$ irb

print "howdy world!" howdy world!=> nil

Classes

A class is a kind of master

object

Can contain constants and

methods

Instances of object can be

created from a class, inheriting the traits of the class

A simple class

class Cat end

(but this class doesn't do or mean anything)

the class examples are derived from http://www.juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/

creating a new cat

Now, I can create an instance

of the cat class: gc = Cat.new("GC", "short hair", "black", "gimpy") lc = Cat.new("LC", "short hair", "black", "little")

add a method

I'd like to be able to describe my cats easily So I add a method to the cat class: def describe @name + " is a " + @color + " "

  • @type + " who is "
  • @attribute + ".\n" end

calling the method

If I call a cat with the

describe method attached, I can get the description of that cat: my_string= gc.describe puts my_string

or:

puts gc.describe

finding cats by name

A second method, find_by_name: def self.find_by_name(name) found = nil ObjectSpace.each_object(Cat) { | o| found = o if o.name == name } found end

Variables

In ruby, vars are references to objects, not objects themselves So: a = "my value" b = a a[0] = "n" will change both a and b--but if you reassign a, eg a="new value", a is linked to a new object (this might bite you, but it's not likely)

Arrays

Create an array by assignment:

my_array = [ "one", "two", 3, 4 ]

Referencing the array:

puts "my_array[0] is: #{my_array[0]}\n"

The brackets are methods of

the array class…