210 likes | 287 Views
Rails Week 4. Ruby Basics by Brendan Kemp — Based on RailsBridge. Housekeeping. Attendance Website: umassrailscourse.wordpress.com Final Project. Ruby Basics Recap. Ruby. Dynamically typed Object oriented Regular Expressions Blocks & lambdas. Time to Play Along.
E N D
Rails Week 4 • Ruby Basics • by Brendan Kemp — Based on RailsBridge
Housekeeping • Attendance • Website: umassrailscourse.wordpress.com • Final Project
Ruby • Dynamically typed • Object oriented • Regular Expressions • Blocks & lambdas
Time to Play Along • IRB — Interactive Ruby Console • Go into Terminal.app and type ‘which irb’ • Type ‘irb’ and get the console • Type ‘ruby ’ + ‘on ’ + ‘rails’ <enter> • What else can you do?
Everything is an Object • Type “test”.upcase • Try “test”.methods • 4.methods • “test”.methods && 4.methods
Methods are Messages • Smalltalk style • Ideally it means that you can send messages without worrying if the method exists • Try: ‘what?’.send(‘upcase’) • 2.+2 • ‘what’.respond_to?(‘+’)
Parentheses are Optional • ‘WHAT?’.send’downcase’ • ‘WHAT?’.send ‘downcase’ • When do you actually use parentheses?
‘#’ starts a comment • 4.send ‘plus’ 4 # adds 4 and 4 • You don’t need semicolons
Method Conventions • Methods ending in ‘?’ return a boolean. • 4.kind_of?(Integer) • Methods ending in ‘!’ change the object value • @what = ‘ what’ • @what.lstrip! • @what
Symbols • :sym is a unique object in Ruby • :sym.object_id • :sym.object_id • ‘string’.object_id • ‘string’.object_id
Arrays • Arrays are sized dynamically, and can be of mixed type. • a = [1, 2, 3, 4] • a.push “Tell me that you love me more” • a # ???
Hashes • Hashes are associative maps. • states = {“MA” => “Massachusetts”, “Mass” => “Massachusetts”} • The key has to be unique • hashes = {:keys => ‘there is one key’, :keys => ‘there is still one key’}
Strings • :sym.to_s • “string” vs ‘string’ • String interpolation • “string #{@ruby_code} string” • “ ‘word’ is an object of class • #{ ‘word’.class}”
Iteration & Blocks • animals = [“cat”, “dog”, “frog”] • animals.each do |animal| • print “This is a #{animal.capitalize}.” • end
Define a method that takes a block • class Array • def method_that_accepts_block • yield • end • def each_third • self.each_with_index do |array_object, i| • yield if (i % 3) == 0 • end • end • end
Iteration for Hashes • animal_info = {:species => ‘cat’, :color => ‘tabby’, :age => 2} • animal_info.each do |key, value| • “My #{key} is #{value}” • end
Classes • class Animal • def animal_that_kills_me #object method • unless self.name == ‘Bear’ • ‘Shark’ • end • end • def self.most_deadly_animal #class mthd • ‘Bear’ • end • end
Variables & Constants • local_variable • method • @instance_variable • CONSTANT
Relational Databases • Databases, Tables, Rows, Attributes • Primary Keys • Associations • has_many • belongs_to • has_and_belong_to_many • self-referential joins