Ruby101

38
Ruby 101 1 Thursday, April 18, 13

description

Beginning ruby for programmers. Overview of ruby covering the basics

Transcript of Ruby101

Page 1: Ruby101

Ruby 101

1

Thursday, April 18, 13

Page 2: Ruby101

Topics

• Ruby Syntax

• Methods/Functions

• DataTypes

• Control Flow

• Exceptions

2

Thursday, April 18, 13

Page 3: Ruby101

Ruby Syntax

3

Thursday, April 18, 13

Page 4: Ruby101

Ruby Syntax• indent 2 spaces, no tabs

• CamelCase for class names

• snake_case_for methods and variables

• filenames always snake case

user_setting.rb

class UserSetting def update_from_params(params) end def save endend 4

Thursday, April 18, 13

Page 5: Ruby101

Ruby Syntax

• comments start with #

• multi-line =begin =end

# one line comment

=begin name = "Bob" address = "123 street" city = "Any Town"=end

5

Thursday, April 18, 13

Page 6: Ruby101

parentheses optional (mostly!)

need them here

else will an OR here

Document.new "The Ruby Way", "Hal Fulton"Document.new("The Ruby Way", "Hal Fulton")

event_date.to_s :shortevent_date.to_s(:short)

if name.blank? puts "Hi nobody"end

if (name.blank? || (name == "bob"))if name.blank? || (name == "bob")

if name.blank? || name == "bob"

6

Thursday, April 18, 13

Page 7: Ruby101

one more thing about parentheses

class User def status #blah blah endend

class User def status() #blah blah endend

always

never

7

Thursday, April 18, 13

Page 8: Ruby101

Variables

8

$global_variable@@class_variable@instance_variableCONSTANT

Thursday, April 18, 13

Page 9: Ruby101

String Interpolation vs String Concatenation

10.times { |n| puts "the number is #{n}" }

String Interpolation, plus reads better

10.times { |n| puts "the number is" + n }

String concatenation, slow-er!

plus calls to_s if not a string

9

Thursday, April 18, 13

Page 10: Ruby101

• code style

• variable/class style

• comments

• role of parentheses

• variables

• string interpolation

10

Learned about Ruby Syntax

Thursday, April 18, 13

Page 11: Ruby101

Methods

11

functions usually called methods

Thursday, April 18, 13

Page 12: Ruby101

Method Return Values

12

def format_name(user) return "#{user.first.capitalize} #{user.last.capitalize}"end

def format_name(user) "#{user.first.capitalize} #{user.last.capitalize}"end

Last line of function is implicit return

Thursday, April 18, 13

Page 13: Ruby101

methods with ? !

13

def validate_user?(user) if user.first.present? && user.last.present? true else false end end

def promote_user!(user, level) user.access = level user.saveend

Thursday, April 18, 13

Page 14: Ruby101

methods with ?

14

> "classified ventures".include?("class") => true> "classified ventures".include?("blah") => false

Use ? as part of the method name if it returns a boolean

Thursday, April 18, 13

Page 15: Ruby101

Using !

15

> company = "classified ventures" => "classified ventures"

> company.upcase => "CLASSIFIED VENTURES"

> company => "classified ventures"

> company.upcase! => "CLASSIFIED VENTURES" > company => "CLASSIFIED VENTURES"

Thursday, April 18, 13

Page 16: Ruby101

Learned about

• ! methods

• ? methods

• return value

16

Thursday, April 18, 13

Page 17: Ruby101

Data Types

Everything is an object

no such idea as “primitives”

17

Thursday, April 18, 13

Page 18: Ruby101

Strings> company = "Classified Ventures" => "Classified Ventures"

> company.length => 19

> company.reverse => "serutneV deifissalC"

> company.upcase => "CLASSIFIED VENTURES"

> company.start_with?("Class") => true

> company.start_with?("Goo") => false

18

Thursday, April 18, 13

Page 19: Ruby101

Symbols> :first => :first

> :first.class => Symbol

Commonly used in Hashes

19

Thursday, April 18, 13

Page 20: Ruby101

Whats the difference?> "hello".object_id => 70312121540820

> "hello".object_id => 70312126306720

> :first.object_id => 32488

> :first.object_id => 32488

20

Thursday, April 18, 13

Page 21: Ruby101

FixNum, BigNum,Booleans > 1.class => Fixnum > 10000000000000000000000000.class => Bignum

> 3.14.class => Float

> true.class => TrueClass

> false.class => FalseClass

21

Thursday, April 18, 13

Page 22: Ruby101

Arraysfruits = ['apple', 'orange', 'pear']

fruits = %w(apple orange pear)=> ['apple', 'orange', 'pear']

a = Array.new(5)=> [nil, nil, nil, nil, nil]

a = Array.new(5, "--")=> ["--", "--", "--", "--", "--"]

22

Thursday, April 18, 13

Page 23: Ruby101

Hashes

default value if key is not found

fruits = {:apple => 5, :orange => 4, :pear => 1}

fruits = { apple: 5, orange: 4, pear: 1 }

fruits[:apple]=> 5

z = {} #default is nila = Hash.new( "--" ) #default is “--”

z[:blah]=> nil

a[:blah]=> "--"

Ruby 1.9

23

Thursday, April 18, 13

Page 24: Ruby101

Struct

24

Crumb = Struct.new(:name, :value) => Crumb

home = Crumb.new("Home", "/") => #<struct Crumb name="Home", value="/">

home => #<struct Crumb name="Home", value="/">

> home.name=> "Home"

> home.value=> "/"

Thursday, April 18, 13

Page 25: Ruby101

Ranges

25

> 1..10 => 1..10

> (1..10).class => Range

> (1..10).to_a (creates array) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > (1...10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9]

two dots includes end point

three dots does not include end point

Thursday, April 18, 13

Page 26: Ruby101

Learned about Datatypes• Strings

• Symbols

• FixNum, BigNum

• Booleans

• Array

• Hash

• Struct

• Ranges

26

Thursday, April 18, 13

Page 28: Ruby101

Classesclass Document attr_accessor :title, :author, :content def initialize(title, author, content) @title = title @author = author @content = content end end

@var is an instance variableaccess it as @var inside class

28

constructor

Thursday, April 18, 13

Page 29: Ruby101

attr_accessormakes getters and setters

class Document # setter def title=(title) @title = title end # getter def title @title end

class Document attr_accessor :titleend

same result

also attr_reader and attr_writer29

Thursday, April 18, 13

Page 30: Ruby101

Example Classclass Document attr_accessor :title, :author def initialize(title, author) @title = title @author = author end

def words @content.split end def self.supported_file_types %w(pdf jpg gif doc) end

end

doc = Document.new("The Ruby Way", "Fulton")doc.wordsDocument.supported_file_types

30

instance method

class method

Thursday, April 18, 13

Page 31: Ruby101

Learned about

• class constructors

• getters/setters

• instance methods

• static methods

31

Thursday, April 18, 13

Page 32: Ruby101

Control Flow

32

Thursday, April 18, 13

Page 33: Ruby101

Code Blocks10.times { |n| puts "the number is #{n}" }

10.times do |n| puts "the number is #{n}" better_for_longer_blocks(n)end

33

item for each iteration is n

Thursday, April 18, 13

Page 34: Ruby101

if / unlessif not @readonly doc.write(text)end

unless @readonly doc.write(text)end

unless @readonly doc.write(text)else log.warn("attempt to write to readonly file")end

doc.write(text) unless @readonly

bad

good

good

bad

34

Thursday, April 18, 13

Page 35: Ruby101

for / eachfruits = ['apple', 'orange', 'pear']

for fruit in fruits puts fruitend

fruits.each do |fruit| puts fruitend

bad

good

35

Thursday, April 18, 13

Page 36: Ruby101

while loops

36

i = 0while i < 5 puts i i += 1end

i = 0until i == 5 puts i i += 1end

puts i += 1 until i == 5

Thursday, April 18, 13

Page 37: Ruby101

Exceptions

37

class Name # Define default getter method, but not setter method. attr_reader :first # When someone tries to set a first name, enforce rules about it. def first=(first) if first.blank? raise ArgumentError.new('Everyone must have a first name.') end @first = first.capitalize endend

def edit name = Name.new name.first = params[:name]rescue ArgumentError => e log.error("Validation Error #{e.message}")end

Thursday, April 18, 13

Page 38: Ruby101

Covered Control Flow

• if/unless

• for/each

• while loops

• exceptions

38

Thursday, April 18, 13