15
Ruby Basic (2) Author: Jason

Ruby basic2

Embed Size (px)

Citation preview

Page 1: Ruby basic2

Ruby Basic (2)Author: Jason

Page 2: Ruby basic2

Content

Method

Regular Expression

Block

Iterator

Convention

Page 3: Ruby basic2

Method

No type in parameter since Ruby is dynamic

last expression value will be returned

But You can explicitly state the return statement

Page 4: Ruby basic2

Method Example

def say_goodnight(name)

"Good night, " + name

end

say_goodnight("jason") # => "Good night, jason"

return

Page 5: Ruby basic2

Common method

Method Usage

print print content with no line break

puts print content with line break

p same as puts but more detailed

Page 6: Ruby basic2

Regular Expression

Ruby is built in with Regular Expression

Regular Expression is also a class in Ruby

patten = /Perl|Python/

patten.class # => Regexp

Page 7: Ruby basic2

Find with Regex

Use =~ to find that String contains pattern or not

line = "Perl"

if line =~ /Perl|Python/

puts "line contain Perl or Python"

end

Page 8: Ruby basic2

Substitution with Regex

line = "Perl, Perl , Perl"

sub : substitute first occurrence

line.sub(/Perl/,"Ruby") # => "Ruby, Perl , Perl"

gsub: substitute all occurrence

line.gsub(/Perl/,"Ruby") # => "Ruby, Ruby , Ruby"

Page 9: Ruby basic2

Block

You may consider block as a anonymous function called by another method

By Convention:

Single expression inside block use {}

Many expressions inside block use do..end

Page 10: Ruby basic2

Block Example

Single expression

{ puts "hello" }

Many expressions

do

puts "hello"

puts "world"

end

Page 11: Ruby basic2

Called by function?def greet

yield

puts "Jason"

end

greet { puts "Hi" }

Result:

Hi

Jason

code in {} will be placed in yield

Page 12: Ruby basic2

Block with argument

def greet

yield("Jason")

end

greet { |name| puts "Hello, #{name}" }

Result: Hello, Jason

PS: It does’t matter what your variable name is inside |..|

"Jason" become name

Page 13: Ruby basic2

Iterator

Many iterator can take a block

Iterator can help you loop though an array and do some operations

A basic iterator is .each which loop all of the element in the array

Page 14: Ruby basic2

Iterator Examplenames = %w{jason sam ray}

names.each do |name|

print "Weclome, "

puts name

end

Result:

Weclome, jason

Weclome, sam

Weclome, ray

Page 15: Ruby basic2

Convention