3. Install
For Windows
http://rubyinstaller.org/
For Mac
Build-in
I strongly recommend you to use Mac or Linux to develop Ruby programs.
But in this tutorial, I am gonna use Windows since I am stiff-necked guy
4. Comment
Comment in Ruby is similar to Perl
Ruby Perl
# comment a line # comment a line
=begin =pod
Comment a block Comment a block
=end =cut
5. Data Types
Numbers puts 1+2 #3
Integer print puts 2*3 #6
puts 5-8 #-3
Float puts 9/2 #4
Letters puts 9.to_f/2 #4.5
String
Cast to float
--------------------------
puts ‘Enter a string’ #Enter a string More:
puts gets.chomp #input from keyboard .to_i
puts 'ha'*3 #hahaha .to_s
puts=<STDOUT>
Repeat 3 times gets=<STDIN>
chomp=delete last char
6. Variables, Arrays, and Iterators
In C/C++, we write int a = 1; in Perl, we write $a = 1; in
Ruby…
a= 1
Yes, just write a
a= 1
b = ‘2’
c = a.to_s + b #12
Cast a to string
Add(+) = conj strings
7. Variables, Arrays, and Iterators
Arrays
[ele1, ele2, ele3]
Some array methods
.pop
.push
.join(‘join string’)
.last
.length
8. Variables, Arrays, and Iterators
There is a special array method : each
iterator
An array with 3 elements
color= [‘R', 'G', 'R']
color.each do | c | | c | = variable in this
puts “color=” + c do…end block
end
Output=
color=R
color=G
color=B
9. Methods
If objects(variables, arrays, …) are nouns in
English, then methods are verbs!
int=noun
We say “int, convert to string” to_s=verb
int.to_s
Sometimes we just say a verb without any noun, ie. GO!
gets
User defined methods
11. Methods
Some number methods
** #exponential
% #modular
.abs #absolute value
rand(number) #generate a random number
srand(seed) #generate a random seed
12. Methods
More on user defined methods, similar to Python!
def functionName (arg1, arg2)
#do something
return ret_val
end
Actually we don’t have to
return because….
Case1: the function doesn’t
have to return
Case2: the last line is the
default return value
13. Flow Control
Conditional flow control
Looping flow control
if condition1 while condition
#do something #do something
elsif condition2 end
#do something
else
#do something
end
Don’t forget end
14. The End
The first part is over, please wait for the second part
Any comments would be appreciated
Welcome to my study page
http://bradyisstudying.blogspot.tw/