75
Ruby Tutorial Mickey Nguyen 1 Ruby Tutorial Written by: Mickey Nguyen (linkedin: [email protected]) 2015

Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

  • Upload
    vandieu

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

1

Ruby Tutorial

Written by: Mickey Nguyen

(linkedin: [email protected])

2015

Page 2: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

2

1 Ruby Installation ................................................................................................................................... 4

2 Introduction ........................................................................................................................................ 12

3 Put, print output, read input from console ........................................................................................ 15

4 String ................................................................................................................................................... 19

5 While loop ........................................................................................................................................... 21

6 Until ..................................................................................................................................................... 23

7 For loop, Each do, redo, retry ............................................................................................................. 25

8 Function .............................................................................................................................................. 28

9 Overloading function .......................................................................................................................... 32

10 if-elsif-else,unless, case ....................................................................................................................... 34

11 Enum ................................................................................................................................................... 36

12 Array .................................................................................................................................................... 37

13 Hash Table ........................................................................................................................................... 39

14 Block .................................................................................................................................................... 41

15 Module ................................................................................................................................................ 43

16 Use local time and calendar ................................................................................................................ 45

17 Bitwise ................................................................................................................................................. 47

18 FileIO ................................................................................................................................................... 49

19 Class .................................................................................................................................................... 51

20 Inheritant ............................................................................................................................................ 53

21 Global and Constant ............................................................................................................................ 55

22 Thread ................................................................................................................................................. 57

23 Networking Socket .............................................................................................................................. 59

23.1 UDP client-server ........................................................................................................................ 59

23.2 TCP client-server ......................................................................................................................... 61

24 Exception Handling ............................................................................................................................. 63

25 Lambda Expression ............................................................................................................................. 65

26 Run Java Code ..................................................................................................................................... 67

26.1 Call Java jar .................................................................................................................................. 67

26.2 Call Java method ......................................................................................................................... 69

27 Regular Expression (Regex) ................................................................................................................. 71

28 XML Processing ................................................................................................................................... 73

Page 3: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

3

29 Database Acess ................................................................................................................................... 75

30 GUI Programming................................................................................................................................ 75

Page 4: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

4

1 Ruby Installation Skip install Eclipse if you installed it already.

I am going to use Eclipse as IDE (Integrated development environment) compiler. Download Eclipse at

http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/luna/R/ecl

ipse-jee-luna-R-win32-x86_64.zip

Save Eclipse zip file in your local, then extract all. After extract all, it looks like this

To launch Eclipse simply just double click on eclipse. Before do this, create a folder in your local drive

name it as “Myworkspace”, you can name it whatever you want. It will be a director contain all of your

work.

Page 5: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

5

You can close the Welcome screen

Page 6: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

6

Now, download Ruby

http://rubyinstaller.org/downloads/

download ruby 2.2.2(x64). Save this exe, run install it, it should creates in C:\Ruby22-x64\bin

Go to Eclipse, Help->marketplaces, search for Ruby, install Ruby DLTK

Page 7: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

7

Page 8: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

8

After install DLTK, from Eclipse, go to Window->references->Interpreter, add the ruby exe in C:\Ruby22-

x64\bin

Click on Add

Page 9: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

9

Now, create a Ruby project

File->New->Other, select Ruby Project

Page 10: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

10

Next, give it a name (whatever name) com.mickey.ruby

Page 11: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

11

Finish

Then, Right click on Project->New->Folder, name it src

Page 12: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

12

2 Introduction This is high level principle concepts of Ruby language.

In Ruby, method name and parameter/variable name are starting with lower case. Otherwise, Ruby will

think uppercase is a constant. Class name must start with uppercase.

Create a first script, right click on Ruby project->New->File

Give it a name PrintPuts.rb

Page 13: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

13

Page 14: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

14

You can copy and paste my code to run it

Page 15: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

15

3 Put, print output, read input from console Syntax:

puts “string” #a string putc ‘c’ #a character puts “\n” #new line puts “string #{variable} string” #use print, printf print “string” print “\n” #new line printf “string %s,%d”,string,number #read input from consol stringname = gets #contain nil termination stringname = gets.chomp #will not contain nil termination Note: you can use () or without it, it is ok Create section3.rb #Note: you can use () or without it, it is ok #output #puts has automatic new line at the end puts "Hello, Mickey!" puts ("Hello, Mickey!") #to print out a single character use putc and single ' ' putc 'a' #did not has new line puts "\n"#new line #use " " is ok, too putc "b" puts "\n" #new line #very much like you do in C, printf("100 *5 =%d",100*5); puts "100 * 5 = #{100 * 5}" puts ("\n") #print out as it raw p "Mickey Nguyen" puts "Mickey Nguyen" #print did not has new line. print "Patrick Nguyen" print ("Patrick Nguyen") print "\n" #add new line print "Sarah Nguyen\n" print "Sarah Nguyen\n"

Page 16: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

16

#using printf printf "Mickey Nguyen is a %s engineer", "SW" print "\n" printf("Mickey is %d years old and %.2f lbs", 50, 179.99) #input print "\n" print "What is your name: " name = gets #get a line of string printf "Hello %s",name #or use puts puts "Hello #{name}" puts ("Hello #{name}") #string size include nil for termination puts "name has #{name.size} characters" #string size has no nil termination print "What is your name again: " name = gets.chomp #eliminate the nil termination printf("name has %d characters without nil termination",name.size) #block comments =begin This is a block of comments I can go on and on on and on =end To Run it, right click on script->Run As->Ruby Script

Page 17: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

17

Output:

Page 18: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

18

Page 19: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

19

4 String Create section4.rb

name = "Mickey Trong Nguyen, he is a software engineer" puts name puts (name.upcase()) puts (name.downcase()) puts (name.capitalize()) #check substring if (name["Nguyen"]) puts ("yes, Nguyen is in it") else puts("No, Nguyen is not in there") end #another way to check substring if name.include? "Nguyen" puts "String includes Nguyen" else puts "There is no Nguyen" end #convert number to string i = 10 puts (i.to_s()) #convert string to number s = "11" puts (s.to_i()+1)

Output:

Page 20: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

20

Page 21: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

21

5 While loop

Syntax:

while (codition) …… end #or do while begin ……… end while (condition) create section5.rb

i = 0 #while loop while (i < 5) # you can use ( ) or not does not a matter print "i: ", i, "\n" i = i + 1 end #Another style, very much like do while i = 0 begin puts "Inside the loop i = #{i}" i +=1 end while i < 5

Output:

Page 22: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

22

Page 23: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

23

6 Until Syntax:

until (condition) do … End #or use until this way, very much like do while begin ….. end until (condition)

Create section6.rb

i = 0 until i > 4 do printf("i: = %d\n",i ) i +=1; end #another way of until, very much like do while i = 0 begin printf("Inside the loop i = %d\n",i) i +=1; end until i > 4

Output:

Page 24: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

24

Page 25: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

25

7 For loop, Each do, redo, retry - Redo, keep redo same index - Retry, go back to first index

Create section7.rb #times do 5.times() do |i| puts i end #for loop in range #In for you can name it i/index/item/whatever, #then in the puts function pass in #{i/whatever you name} for i in 0..5 puts "i: #{i}" end print("\n") #or use do each item in range #again, you can name it i or whatever, #then in the puts function pass in whatever you name it (0..5).each do |item| puts "each item in range, item is: #{item}" end print("\n") #use break condition for i in 0..5 if (i >= 3) break end puts "i must less than 3, i: #{i}" end print("\n") #use next to skip one index for index in 0..5 if (i == 3) next end puts "index: #{index}" #will not print out 3 end print("\n") #use redo to repeat j = 0 for i in 0..5 if (i == 3) j +=1 if (j < 3) # restrict redo 2 times, otherwise it will redo 3 forever puts "i: #{i}" redo end

Page 26: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

26

end end print("\n") #use rescue to restart from first index again begin (1..10).each do |x| puts x if x > 6 STDIN.gets # press enter to do another iteration raise "oops x is over 6" end end rescue retry end print("\n")

Output:

Page 27: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

27

Page 28: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

28

8 Function In Ruby, method name and parameter name are starting with lower case. Otherwise, Ruby will think

uppercase is a constant.

Syntax:

def functionName() #function without parameter ……… end def functionNanme(par1,par2,..,parn) #function with parameters …. end creae section8.rb #define a func without parameter def myFirstFunc() print("This is my first function") end #call function myFirstFunc() print("\n") #function return a string #compiler smart to know name has string data type def sayHello (name) var = "Hello " + name return var end puts sayHello("Mickey Nguyen") #define a func has parameters but return void #compiler smart to know x and y are numbers def mySecondFunc(x,y) result =x+y printf("The sum of %d and %d is %d.",x,y,result) end #call function mySecondFunc(5,10) print("\n") #define a function has parameters and a return value #compiler smart to know x and y are numbers def myThirdFunc(x,y) return x+y end #call function print(myThirdFunc(3,4)) print ("\n")

Page 29: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

29

#define another func has parameters and a return value #compiler smart to know parameters are string type #and function return a string def myFourFunc(firstName, lastName, middle) myname = firstName + " "+ middle + " "+ lastName return myname end print(myFourFunc("Mickey","Nguyen","Trong")) print("\n") #Function return value def sum (a,b) return a+b end #call function total = sum(5,10) print(total) print("\n") #Use * in function argument, #it is not a pointer, it is an array def addUp (x,y,*moreNumbers) #local var numbers numbers = 0 arraylen = moreNumbers.length arraylen = arraylen -1 #start of 0 for i in 0..(arraylen) #go thru length of array , sum up numbers += moreNumbers[i] end return x + y + numbers end puts addUp(1,2,4,5,6,7) print("\n") #second way to implement * def addUp2 (x,y,*moreNumbers) #sum and number is two variables, number is 4,5,6,7 numbers = moreNumbers.inject(0) { |sum, number| sum +=number } return x + y + numbers end puts addUp2(1,2,4,5,6,7) print("\n") #ParameterHasDefaultValue def person(name="Mickey",age =50) puts(name) puts(age) end #Call without pass in parameters. to use default value person() #call with pass in parameters person("Patrick Nguyen", 4) print("\n")

Page 30: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

30

#Function can return multiple items def employee (name, age, gender) return name, age, gender end var = employee("Mickey Nguyen",50,"Male") puts(var) print("\n") #read out each item for item in var puts (item) end #another way to call for mutiple return myname, myage, mygender = employee("Patrick Nguyen",4,"Male") puts myname puts myage puts mygender

Output:

Page 31: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

31

Page 32: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

32

9 Overloading function Ruby did not support overloading function but we in some case, if the parameters are same data type,

then we can work around like this

Create section9.rb

def FunctionOverloadForNum (*whatever) #whatever can be one, two, three, more parameters numbers = whatever.inject(0) { |sum, number| sum +=number } return numbers end def FunctionOverloadForStr (*whatever) #whatever can be one, two, three, more parameters longStr = whatever.inject("") { |output, str| output +=str } return longStr end #Call for overload numbers puts FunctionOverloadForNum(1) #you can see I have a long list of parameters of same function name puts FunctionOverloadForNum(1,2,3,4,5) #call for overload string puts FunctionOverloadForStr("Mickey Nguyen") #you can see I have a long list of parameters of same function name puts FunctionOverloadForStr("He"," is"," a sw"," engineer with ",17.to_s()," years of experience" ) Output:

Page 33: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

33

Page 34: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

34

10 if-elsif-else,unless, case Syntax:

if ... elsif … else … end unless …. else …. end case when … When …. Else … end create section10.rb

a = 5 b = 6 c = 7 #if-elsif-else if a > b print("Yes, a is > b") elsif (a > c) print("Yes, a is > c") else print("No, a is < b and c") end #or just compare one case like this print("\n") puts("Yes, a == 5") if (a==5) #you will not see this print out puts("No, b = 6") if (b==7) #unless unless a >= b #false condition puts("No, a is < b") else #true condition

Page 35: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

35

puts("Yes, a > b") end #case name = "Mickey" case name when "Patrick" puts "Patrick Nguyen" when "Mickey" puts("Mickey Nguyen") else puts("Unknow name") end

Page 36: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

36

11 Enum

Create section11.rb

class Colors include Enumerable def each yield "red" yield "green" yield "blue" end end c = Colors.new #loop thru each and print it out c.each() {|color| puts color}

Page 37: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

37

12 Array Create section12.rb

#array of string name = Array.new(4) name.insert(0,"Mickey") #index 0 name.insert(1,"Patrick") name.insert(2,"Sarah") name.insert(3,"Chau") for item in name puts (item) end #array of number number = Array.new(4) number.insert(0,1) #index 0 number.insert(1,2) number.insert(2,3) number.insert(3,4) for item in number puts (item) end print("\n") #array of everything, mix them up everything = Array.new(5) everything.insert(0,"Luna") everything.insert(1,21) everything.insert(2, 110.00) everything.insert(3,"Nurse") everything.insert(4,"Single") for item in everything puts (item) end print("\n") #another way of create and initialize an array nums = Array[1, 2, 3, 4,] puts (nums) print("\n") #another way of create and initialize an array nums = Array.[](5, 6, 7, 8) puts (nums) print("\n") #another way of create and initialize an array nums = Array(10..13) puts (nums)

Page 38: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

38

print("\n") #another way of create array myarray = [] #empty myarray << 8 myarray << 9 myarray << 10 myarray << 11 for item in myarray puts(item) end

print("\n") #range to Array myArry = (1..10).to_a() for item in myArry puts(item) end

Output:

Page 39: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

39

13 Hash Table

Create section13.rb

#create a hash table items = Hash.new() # Store these key-value pairs in it. items["milk"] = 2 items["eggs"] = 4 items["beer"] = 21 # Display the values. puts (items["milk"]) puts (items["eggs"]) puts (items["beer"]) #another way to create a hash table values = {"cat" => 1, "dog" => 2, "rabbit" => 4} # Display the values. puts (values["cat"]) puts (values["dog"]) puts (values["rabbit"]) #Mix everything up everything = Hash.new() everything["twenty one"] = "Beer" everything[12] ="Dozen of eggs" everything["Mickey"] = 189.99 puts (everything["twenty one"]) puts (everything[12]) puts (everything["Mickey"])

Page 40: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

40

Page 41: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

41

14 Block Syntax:

#using yield to call block def block_name yield #call block yield #call block end block_name {#block implementation} #using & last parameter to call block def block_name(parameter1,… &lastparameter) lastparameter .call end block_name {#block implementation} Create section14.rb

#using yield to call block def call_block puts 'Start of method' puts ("I am Mickey Nguyen") # you can call the block using the yield keyword #will do whatever you setup in the call block yield yield yield puts ("I am Patrick Nguyen") puts 'End of method' end # Code blocks may appear only in the source adjacent to a method call call_block {puts 'In the block'} print("\n") # can pass parameters to a block def test_block yield 5, 10 puts "You are in the method test" yield 10, 20 end #|i,j| are variables test_block {|i, j| puts "You are in the block, sum of i and j is #{i+j}"} print("\n") #Another way to call block using & in the very last parameter. Not using yield this for call block def test_block2(names, &block) if block_given? names.each {|name| block.call(name)} end

Page 42: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

42

puts "No block given" end test_block2(["Mickey Nguyen", "Patrick Nguyen","Sarah Nguyen"]) {|name| puts name + " Hello World!"} print("\n") test_block2(["Luna Nguyen"]) print("\n") #Just only & parameter def test_block3(&block) block.call block.call block.call end test_block3 { puts "Hello World!"} Output:

Page 43: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

43

15 Module Define module, then module can be included in other module. Use class to access to method define in

module.

Create section15.rb

module MyPrint def MyPrint.print1(name, age, weigh) puts(name) puts(age) puts(weigh) end #did not use MyPrint.print2 def print2() puts("This is Print2") end end module MyInfo #include another module name MyPrint include MyPrint def moduleInfo puts "I am a software engineer" MyPrint.print1("Mickey Nguyen", 50, 189.99) #Cannot call MyPrint.print2 because it did not define as Myprint.print2 end end #class in order to access to module and its method class MyClass #include module name MyInfo include MyInfo end #class access to method of MyInfo module MyClass.new.moduleInfo() #class access to method of MyPrint module thru MyInfo module MyClass.new.print2() #cannot call MyClass.new.print1 because it defined as MyPrint.print1

Output:

Page 44: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

44

Page 45: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

45

16 Use local time and calendar Create section16.rb

time1 = Time.new puts "Current Time : " + time1.inspect # Time.now is a synonym: time2 = Time.now puts "Current Time : " + time2.inspect # Components of a Time puts "Current Time : " + time1.inspect puts time1.year # => Year of the date puts time1.month # => Month of the date (1 to 12) puts time1.day # => Day of the date (1 to 31 ) puts time1.wday # => 0: Day of week: 0 is Sunday puts time1.yday # => 365: Day of year puts time1.hour # => 23: 24-hour clock puts time1.min # => 59 puts time1.sec # => 59 puts time1.usec # => 999999: microseconds puts time1.zone # => timezone name #put time into array time = Time.new values = time.to_a p (values) puts (values)

Output:

Page 46: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

46

Page 47: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

47

17 Bitwise

Create section17.rb

a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0 c = a & b; # 12 = 0000 1100 printf("Line 1 - Value of c is %d", c) print("\n") c = a | b; # 61 = 0011 1101 puts("Line 2 - Value of c is #{c}") c = a ^ b; # 49 = 0011 0001 puts("Line 3 - Value of c is #{c}") c = ~a; # -61 = 1100 0011 puts ("Line 4 - Value of c is #{c}") c = a << 2; # 240 = 1111 0000 puts("Line 5 - Value of c is #{c}") c = a >> 2; # 15 = 0000 1111 puts("Line 6 - Value of c is #{c}") #exercise some hex Value num = 2015 puts (num.to_s(16)) puts ("%04x" %num) puts ("%08x" %num) puts sprintf("%04X", num) puts sprintf("%08X", num)

Output:

Page 48: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

48

Page 49: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

49

18 FileIO

Create section18.rb

#Open a file and write some texts to it fname = "info.txt" file = File.open(fname, "w") file.puts "Hello file!" file.puts("I am Mickey Nguyen") file.puts("I am Patrick Nguyen") file.close #Open a file and read it back, read all lines at one shot file = File.open("info.txt", "r") file.readlines.each do |line| puts line end file.close #read back line by line file = File.open("info.txt", "r") while !file.eof? line = file.readline puts line end file.close

Output:

Page 50: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

50

Page 51: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

51

19 Class

Create section19.rb

#create a class class Sample def hello puts "Hello Ruby!" end end # Now using above class to create objects object = Sample.new object.hello print "\n" #add new line class Sample2 @name @age #constructor public def initialize(myName,myAge) @name = myName @age =myAge end def display puts "Name is #{@name}" puts "Age is #{@age}" end end obj = Sample2.new("Mickey Nguyen",50) obj.display() print "\n" #add new line #reinitialize obj.initialize("Patrick Nguyen",4) obj.display() print "\n" #add new line #without implement initialize #then when create object instance, do not pass in any parameter class Sample3 @name @age #@@ have to have to initialize before use it @@weigh = 0.0 public def setParameters(name, age, weigh) @name = name @age = age @@weigh = weigh end def display puts "Name is #{@name}" puts "Age is #{@age}" end def displayWeigh

Page 52: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

52

puts "Weigh is #{@@weigh}" end end print "\n" #add new line #did not implement initialize, cannot set any attribute oj = Sample3.new() #call before set value oj.display() oj.displayWeigh() print "\n" #add new line oj.setParameters("Peter Nguyen",22,189.99) oj.display() oj.displayWeigh()

output:

Page 53: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

53

20 Inheritant

Create section20.rb #Parent class class Mom def momAssets puts "3333 Wayne RD." puts "$9999.99" puts "Lexus" end def hobbies puts "Shopping" puts "Go out to eat" end end #child class inherit from parent class Child < Mom #empty child end #child class inherit from parent class Child2 < Mom def hobbies puts "Fishing" puts "stay home watch TV" end end #parent p = Mom.new p.momAssets() p.hobbies() #child1 object = Child.new object.momAssets()#child not have this method, but it can call from parent #child2 object2 = Child2.new object2.momAssets()#child not have this method, but it can call from parent object2.hobbies()#will override parent hobbies

Output:

Page 54: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

54

Page 55: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

55

21 Global and Constant Create section21.rb

#define global variable $myglobalNumber = 100 def sum (x,y) return x+y+$myglobalNumber end puts sum(5,10) class TestConstant #define some constant AGE = 50 NAME = "Mickey Nguyen" def show puts "Value of first Constant is #{AGE}" puts "Value of second Constant is #{NAME}" end end # Create Objects object=TestConstant.new() object.show

Output:

Page 56: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

56

Page 57: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

57

22 Thread

Create section22.rb

def CallBack1 i=0 while i<=2 puts "func1, pretending working hard here" sleep(2) i=i+1 end end def CallBack2 j=0 while j<=2 puts "func2, pretending doing hard work here" sleep(1) j=j+1 end end puts "Started At #{Time.now}" t1=Thread.new{CallBack1()} t2=Thread.new{CallBack2()} t1.join t2.join puts "End at #{Time.now}"

Output:

Page 58: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

58

Page 59: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

59

23 Networking Socket

23.1 UDP client-server Create section23_1UDPServer.rb

require 'socket' s = UDPSocket.new s.bind(nil, 1234) #'0.0.0.0' data, addr = s.recvfrom(1024) # buffer size is 1024 bytes puts("received message:", data)

Create section23_1UDPClient.rb require 'socket' sock = UDPSocket.new data = "Client sent this" sock.send(data, 0, '127.0.0.1', 1234) sock.close

To test it, start the server first, then start the client. Check server out put

Page 60: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

60

Page 61: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

61

23.2 TCP client-server Create section23_2TCPServer.rb

require 'socket' s = TCPServer.new('', 4321) # '' or '0.0.0.0', port 4321 connection = s.accept puts "received:" + connection.recv(1024) connection.close

Create section23_2TCPClient.rb

require 'socket' s = TCPSocket.new('127.0.0.1', 4321) s.write "hi server!" s.close Run it, start the server first, then start the client, look into server output

Page 62: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

62

Page 63: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

63

24 Exception Handling Create section24.rb

begin # Try to divide by zero. i = 1 / 0 rescue ZeroDivisionError # Handle the error. puts "ERROR" i = 0 end # Display final value. puts i #raise begin # This is a bad program. raise "Error, error" rescue RuntimeError => e # This prints the error message. puts e end #throw-catch def myMethod(a) puts a # Throw on a negative number. if a < 0 throw :negative end end # These statements continue until :negative is thrown. catch :negative do myMethod(0) myMethod(-1) myMethod(1) end puts "END" Output:

Page 64: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

64

Page 65: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

65

25 Lambda Expression

Create section25.rb

#normal function def sayHello puts "Hello world from Mickey Nguyen!" end sayHello #now with lambda, I don't have to define the function sayHello test = lambda {"Hello world from lambda!"} puts test.call #another normal function def sum(x,y) printf("The sum of %d and %d is %d.",x,y,(x+y)) end sum(5,10) #now with lambda, I don't have to define the function sum print("\n") test2 = lambda {|x , y| printf("The sum of %d and %d is %d.",x,y,(x+y))} test2.call(10,20) #another normal function def employee (name,age,gender) puts name puts age puts gender end print("\n") employee("Mickey Nguyen",50,"male") #now with lambda, I don't have to define the function employee test3 = lambda {|name,age,gender| "#{name}\n#{age}\n#{gender}"} puts test3.call("Patrick Nguyen",4,"male")

Output:

Page 66: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

66

Page 67: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

67

26 Run Java Code Download JRuby to work with Java. http://jruby.org/download. From Eclipse->window->reference-

>Ruby->interpreters->add JRuby in.

26.1 Call Java jar Here is Java code:

import javax.swing.JOptionPane; //import class JOptionPane public class hellomickey { public void printmk() { JOptionPane.showMessageDialog (null,"Hello hello from Mickey Nguyen \nHow are you doing today? " ); } public static void main(String[] args) { //JOptionPane.showMessageDialog (null,"Hello hello from Mickey Nguyen \nHow are you doing today? " ); hellomickey mk = new hellomickey(); mk.printmk(); } }

Compile Java code in Java project, Then export to Runable JAR file: hellomickeyr.jar, copy jar

file to under project folder

Here is Ruby script.

Create section26_1.rb

def externaljar() system("C:\\Program Files\\Java\\jdk1.7.0_65\\bin\\java -jar hellomickeyr.jar") #or you can run like this if you already set Java path in environment already #system("java -jar hellomickeyr.jar") puts "Mickey, hello!" end externaljar()

Output:

Page 68: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

68

Page 69: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

69

26.2 Call Java method Create a java project, compile into jar file, copy jar file to under project folder Java code import javax.swing.JOptionPane; //import class JOptionPane public class hellomickey { public void printmk() { JOptionPane.showMessageDialog (null,"Hello hello from Mickey Nguyen \nHow are you doing today? " ); } public static void main(String[] args) { //JOptionPane.showMessageDialog (null,"Hello hello from Mickey Nguyen \nHow are you doing today? " ); hellomickey mk = new hellomickey(); mk.printmk(); } }

Ruby script: Create section26_2.rb require 'java' require 'hellomickey.jar' class Main def run sayObj = Java::hellomickey.new sayObj.printmk() puts "Mickey, hello!" end end app = Main.new() app.run()

Output:

Page 70: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

70

Page 71: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

71

27 Regular Expression (Regex)

Create section27.rb

mystring = "I am Mickey Nguyen. I am a software engineer" #use =~ operation #check for match puts /Mickey/ =~ mystring #another way check for match puts mystring =~ /Mickey/ #use !~ operation #check for not match puts /Mickey/ !~ mystring puts /Patrick/ !~ mystring #use match operation result = /Mickey/.match(mystring) puts result if (result != nil) puts result.pre_match puts result.post_match() end result = /Patrick/.match(mystring) if (result == nil) puts "Did not find match for Patrick" end puts result #Another example result = /1 \+ 2 = 3\?/.match('Does 1 + 2 = 3?') puts result mysubString = "Nguyen" #using #{} result = /#{mysubString}/.match(mystring) puts result

Output:

Page 72: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

72

Page 73: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

73

28 XML Processing Copy nguyenfamily.xml to under project folder

<family nguyen="family members"> <member name="Mickey Nguyen"> <profession>SW Engineer</profession> <age>50</age> <gender>male</gender> </member> <member name="Chau Nguyen"> <profession>SQA Engineer</profession> <age>20</age> <gender>female</gender> </member> <member name="Patrick Nguyen"> <profession>nhoc con</profession> <age>4</age> <gender>male</gender> </member> <member name="Sarah Nguyen"> <profession>student</profession> <age>8</age> <gender>female</gender> </member> </family>

Here is ruby code to parse xml

Create section28.rb

require 'rexml/document' include REXML xmlfile = File.new("nguyenfamily.xml") xmldoc = Document.new(xmlfile) # Now get the root element root = xmldoc.root puts "Root element : " + root.attributes["nguyen"] # This will output all the member name. xmldoc.elements.each("family/member"){ |e| puts "Name : " + e.attributes["name"] } # This will output all the profession. xmldoc.elements.each("family/member/profession") { |e| puts "profession : " + e.text

Page 74: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

74

} # This will output all the movie description. xmldoc.elements.each("family/member/age") { |e| puts "age : " + e.text } # This will output all the profession. xmldoc.elements.each("family/member/gender") { |e| puts "gender : " + e.text }

Output:

Page 75: Ruby Tutorial - storage.googleapis.com · Ruby Tutorial Mickey Nguyen 4 1 Ruby Installation Skip install Eclipse if you installed it already. I am going to use Eclipse as IDE (Integrated

Ruby Tutorial Mickey Nguyen

75

29 Database Acess TBD

30 GUI Programming TBD