Course Overview and Intro to Ruby INFO 2310: Topics in Web Design and Programming.
Ruby Intro
-
Upload
angelo-van-der-sijpt -
Category
Technology
-
view
1.753 -
download
6
description
Transcript of Ruby Intro
Ruby
• Japan, 1993
• Perl, Smalltalk, Lisp
• Readability, writability
• English language, 1999
• Windows, Linux, Mac OS X
• Included with Apple developer tools
• “Everything is an object.”• Except for primiNves. But you can box those.
• Arrays are special.
• Classes are a liQle special, too.
• “Everything is an object.”• Period.
1.class # => Fixnum'a'.class # => String:z.class # => Symbol
class Fooend
Foo.class # => ClassFoo.new.class # => Foo
Everything is an object
Dynamically typeddef do_stuff(thing) thing.do_the_stuffend
class TheThing def do_the_stuff puts "Stuff was done!" endend
do_stuff(TheThing.new)
Dynamically typed
t = TheThing.newt.respond_to? :do_the_stuff # => true
def do_stuff(thing) if thing.respond_to? :do_the_stuff thing.do_the_stuff else raise "What on earth is this?" endend
The language
Strings & variables
name = 'World' # => "World"
"Hello, #{name}" # => "Hello, World"
'Hello, #{name}' # => "Hello, \#{name}"
Every expression has a value
def say_it_isnt_so(really = false) if really "All's fine!" else "All your base are belong to us." endend
say_it_isnt_so # => "All your base are belong to us."say_it_isnt_so true # => "All's fine!"
Return
def do_complicated_stuff(take_shortcut) if take_shortcut return 42 end do_really_complicated_stuffend
Numbers
1 + 1 # => 21 + 1.1 # => 2.16 * 7 # => 426 ** 7 # => 279936
Math.sqrt(65536) # => 256.0
1.class # => Fixnum(2 ** 42).class # => Fixnum(2 ** 64).class # => Bignum
1.1.class # => Float
Arrays
Array.new # => []Array.new(3) # => [nil, nil, nil][] # => []
a = [1,2,3] # => [1, 2, 3]a[0] = 'one' # => "one"a # => ["one", 2, 3]a[-1] # => 3a[1..2] # => [2, 3]
Arrays
a = [1,2,3] # => [1, 2, 3]
a.push 4 # => ["one", 2, 3, 4]a.pop # => 4a # => ["one", 2, 3]
[1,2,3] | [2, 4] # => [1, 2, 3, 4][1,2,3] & [2, 4] # => [2]
Hashes
Hash.new # => {}{} # => {}
h = {1 => "one", 2 => "two"}h[1] # => "one"h["1"] # => nil
h[:one] = "einz" # => "einz"h[:one] # => "einz"
h.keys # => [1, 2, :one]h.values # => ["one", "two", "einz"]
Fun with arrays & hashes
def do_stuff(options = {}) puts options[:hello] if options.include?(:hello)end
do_stuff# => nildo_stuff :hello => "hi"# hi# => nil
Fun with arrays & hashes
[1,2,3,5,7].select {|x| x.even?}# => [2]
[1,2,3,5,7].inject(1) { |x, n| n * x}# => 210
[1,2,3,5,7].map { |n| n * n }# => [1, 4, 9, 25, 49]
{1 => "one", 2 => "two"}.map { |k,v| v }# => ["one", "two"]
Control structures
if condition # ...elsif other_condition # ...end
unless condition # ...end
while # ...end
Control structures
case (1024)when 42 then puts "my favorite number"when 2 then puts "my second favorite number"when 1024, 2048 then puts "fair enough"else "this number sucks"end
Control structures
puts "How are you gentlemen!!" if role.cats?
puts "mommy!" while reaction_from_mommy.nil?
Classesclass Pet attr_accessor :name def initialize(name) @name = name end def sit! puts "Wuff" endend
fido = Pet.new("fido") # => #<Pet:0x10116e908 @name="fido">fido.name # => "fido"fido.sit! # => "Wuff"
Classes
class Cat < Pet def sit! if rand(10) > 8 # decide our mood super else puts "No way!" end endend
mimi = Cat.new("mimi") # => #<Cat:0x101131d00 @name="mimi">mimi.sit! # => "No way!"
Classes
class Cat def self.purr puts "Huh, what? I'm the class!" end def purr puts "prrrrrrr" endend
Cat.purr# "Huh, what? I'm the class!"Cat.new("mimi").purr# prrrrrrr
Classes
class Fixnum def even? return false if eql? 2 super endend
2.even? # => false4.even? # => true
Modules
module ThingsDoer def do_one_thing puts "doing one thing" endend
ThingsDoer::do_one_thing# "doing one thing"
# Modules can be used to group methods, classes or other modules
Modules
class Pet include ThingsDoerend
# we had a Pet instance of fido
fido.do_one_thing# "doing one thing"
Naming convenDons
CamelCased # Classes, moduleswith_underscores # methods, local variables
@instance_variable@@class_variable$GLOBAL_VARIABLE
Code blocks[1,2,3,5,7].select {|x| x.even?}# => [2]
def do_random_nr_of_times &block nr = rand(10) for i in 1..nr yield endend
do_random_nr_of_times { puts "bla" }# bla# bla# bla# => 1..3
Code blocks
def run value = "bla" do_random_nr_of_times { puts value }endrun# bla# bla# => 1..2
Code blocks
the_time = Time.now # Sun Nov 29 20:15:47 0100 2009the_time# Sun Nov 29 20:15:47 0100 2009the_time# Sun Nov 29 20:15:47 0100 2009 >> the_time = lambda { Time.now }# => #<Proc:0x0000000100567178@(irb):463>the_time.call# Sun Nov 29 20:18:16 0100 2009the_time.call# Sun Nov 29 20:18:20 0100 2009
OpDonal language elements
def my_method(data, options = {}) # ...end
# Full signaturemy_method("bla", {:option => 'value', :two => 2})# The last parameter a hash? implicit.my_method("bla", :option => 'value', :two => 2) # Parentheses are optionalmy_method "bla", :option => 'value', :two => 2
# As long as its unambiguous, it's OK
Regular expressions
s = "Ruby rules"# => "Ruby rules"s =~ /rules/# => 5s.gsub(/es/, "ez")# => "Ruby rulez"s.gsub(/[aeiou]/, "*")# => "R*by r*l*s"m = s.match(/([aeiou][^aeiou])/)# => #<MatchData "ub" 1:"ub">m[0]# => "ub"
ExcepDonsbegin raise "Someone set us up the bomb."rescue => e puts e.inspectend# <RuntimeError: Someone set us up the bomb.>
begin raise StandardError.new("For great justice.")rescue StandardError puts "standard"rescue RuntimeError puts "runtime"end# standard
• No threading (at least, by default)
• Only false and nil are not true
What’s more?
def my_method(my_object) puts my_object && my_object.to_sendmy_method(1) # => 1my_method(nil) # => nil
h[:bla] ||= "bla"
Tools
irb
Textmate
What haven’t I talked about?
• TesNng
• RSpec
• DocumentaNon
• RDoc
What haven’t I talked about?
• Gems
• Like ‘apt’ for ruby
• Deployment
• SVN
• Capistrano
What haven’t I talked about?
class BlogPost < ActiveRecord::Base belongs_to :user has_many :comments validates_presence_of :user_id validates_associated :user validates_length_of :title, :within => 10..100 validates_length_of :body, :within => 100..5000end
BlogPost.new(:title -> "My first blog", :body => "is way too short.")
What haven’t I talked about?
• Ruby on Rails
• Web framework
• Strict MVC separaNon
• Handles persistence http://pragprog.com/titles/rails2
module Ruby include(DynamicLanguage) include(ObjectOriented) include(DuckTyping)
def ruby @everything_is_an_object = true end def language {"hashes" => :awesome, "array" => :awesome} value = 'supported' "String variable substibution is #{value}" end
def tools {:editor => 'Textmate', :runtime => 'included in OS X'} endend
thank_audience :speaker => 'Angelo vd Sijpt', :greeting => 'You were awesome!', :find_more_at ['ruby-lang.org', 'rubyists.eu']