Ruby basic

Preview:

Citation preview

Ruby Basic(1)Author: Jason

Content

Feature

String

Array

Hash

Symbol

Control Struct

Feature

Nearly 100% Object-Oriented

Dynamic

No need to compile

Object-oriented

1.class # => Fixnum

1.2.class # => Float

true.class # => TrueClass

Dynamic

a = "String abc"

a.class # => String

a = 10

a.class # => Fixnum

No need to compile

Enter irb in cmd/terminal

play with Ruby!!

String types

Single quote

Just to store character

Better in performance

Double quote

Store binary value, eg: \n

Execute Ruby code in #{}

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

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

Array(2)

Short cut to create String Array:

a = %w{jason sam ray}

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

Hash

Similar to associative array

Key & Value

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

score['jason'] # => 10

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

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

Unique in value

n = :north

n2 = :north

if n == n2

puts "n is equal to n2"

end

• Results : n is equal to n2

Same object ID

n = :north

n2 = :north

n.object_id # => 292808

n2.object_id # => 292808

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

Control Structure(1)

if jason == 'jason'

puts "I am Jason"

end

Control Structure(2)

if jason == 'jason'

puts "I am not Jason"

else

puts "I am Jason"

end

Control Structure(3)

if jason == 'jason'

puts "I am not Jason"

elsif jason == 'handsome'

puts "Jason is handsome"

else

puts "I am Jason"

end

Control Structure(4)

while jason < 100 and jason > 50

jason = jason +1

end

and is equal to &&

or is equal to ||

Recommended