2008年3月4日 星期二

ruby basic

start ruby:
irb

file extension:
.rb

run ruby file:
ex: ruby test.rb

define class, member and method:
class Animal
attr_accessor :name, :age
def bark
puts "bark"
end
end

member is defined by attr_accessor
method is defined by def

another getter/setter method:
ex: def face=(x)
@face=x
end
def face
@face
end

define method with parameter
def test(x, y)
puts "hello"
end

class member
ex: @@a=0


class method:
ex: class Car
@@window=0;
def self.add
@@window= @@window+1
end
end


new object
ex: test= Animal.new
test.name = "peter"
test.bark

print:
use print( 印完後在同一行)
ex: print "hello"

use puts (印完後在下一行)
ex: puts "hello"

inheritance:
class Dog < Animal
attr_accessor :voice
end

show class:
ex: dog.class

string method:
ex: "helllo".length
--> 5

if and unless:
unless is the opposite of if
ex: puts "hello" unless a > 3

loop:
ex: (1) 5.times do puts "test" end
(2) 5.times { puts "test" }
"test" is printed 5 times

ex: (3) 1.upto(5) { |number| puts number } // from 1 to 5, number is the parameter
(4) 10.downto(5){ } // from 10 to 5
(5) 0.step(50,5){ } // from 0 to 50, step is 5

constant:
variable name that begins with a capital letter
ex: Pi

conversion between int and float
x.to_f : int to float
x.to_i : float to int

char and ASCII number:
puts ?x // get x's ascii number
puts 120.chr // get ascii 120's char

embedded expressions in string:
ex: puts "#{x} + #{y} = #{x +y}"
use # and { } to include expression. Expression is calculated first and then translated to string


convert number to string:
ex: x.to_s

substitution:
ex; "foobarbar".sub('bar', 'abc')
---> fooabcbar
"foobarbar".sub(bar, 'abc')
---> fooabcabc

comment :
use #

if a method will modify something, it is commonly suffixed with !
ex: fox.upcase!
fox become FOX

if a method return boolean values, it is commonly suffixed with?
ex: fox.empty?

initialize method is call when an object is instantiated

watch doc:
ri with something you want to find
ex: ri Array

return:
when defining method in ruby, return is optional
because the last expression of the method return by default

沒有留言: