20
Ruby Basic(1) Author: Jason

Ruby basic

Embed Size (px)

Citation preview

Page 1: Ruby basic

Ruby Basic(1)Author: Jason

Page 2: Ruby basic

Content

Feature

String

Array

Hash

Symbol

Control Struct

Page 3: Ruby basic

Feature

Nearly 100% Object-Oriented

Dynamic

No need to compile

Page 4: Ruby basic

Object-oriented

1.class # => Fixnum

1.2.class # => Float

true.class # => TrueClass

Page 5: Ruby basic

Dynamic

a = "String abc"

a.class # => String

a = 10

a.class # => Fixnum

Page 6: Ruby basic

No need to compile

Enter irb in cmd/terminal

play with Ruby!!

Page 7: Ruby basic

String types

Single quote

Just to store character

Better in performance

Double quote

Store binary value, eg: \n

Execute Ruby code in #{}

Page 8: Ruby basic

String Example

v = "double"

s = 'I am a single quote String' # => "I am a single quote String"

s = "I am a #{v} quote String" # => "I am a double quote String"

#{} is to execute the ruby code

Page 9: Ruby basic

Array(1)

Contain a list of item

The elements can be any type

a = [1, 'count', 3.14]

a[0] # => 1

a[-1] # => 3.14

Page 10: Ruby basic

Array(2)

Short cut to create String Array:

a = %w{jason sam ray}

a # => ["jason", "sam", "ray"]

Page 11: Ruby basic

Hash

Similar to associative array

Key & Value

score = {'jason' => 10, 'ray' => 9, 'sam' => 1}

score['jason'] # => 10

Page 12: Ruby basic

Symbol(1)

They are String

Use as identify

Unique in value (handled by Ruby)

Same object id

All methods and variables have its own symbol

Page 13: Ruby basic

Symbol(2)

In Java, we define somethings like

int NORTH = 1

int EAST = 2

In Ruby you just use :north, and :east to act as identify, they should be unique in value

Page 14: Ruby basic

Unique in value

n = :north

n2 = :north

if n == n2

puts "n is equal to n2"

end

• Results : n is equal to n2

Page 15: Ruby basic

Same object ID

n = :north

n2 = :north

n.object_id # => 292808

n2.object_id # => 292808

Page 16: Ruby basic

Symbol in Hash

Symbol usually acts as key in hash to save memory.

Ruby 1.8:

score = {:jason => 10, :ray =>4, :sam => 1}

Ruby 1.9, you can also:

score = {jason: 10, ray: 4 ,sam: 1}

score[:jason] # => 10

Page 17: Ruby basic

Control Structure(1)

if jason == 'jason'

puts "I am Jason"

end

Page 18: Ruby basic

Control Structure(2)

if jason == 'jason'

puts "I am not Jason"

else

puts "I am Jason"

end

Page 19: Ruby basic

Control Structure(3)

if jason == 'jason'

puts "I am not Jason"

elsif jason == 'handsome'

puts "Jason is handsome"

else

puts "I am Jason"

end

Page 20: Ruby basic

Control Structure(4)

while jason < 100 and jason > 50

jason = jason +1

end

and is equal to &&

or is equal to ||