2008年5月26日 星期一

symbol

change string to symbol:
use to_sym or intern
ex:
"test".to_sym
--->  :test

change symbol to string
method 1: use to_s
method 2: use #{ }
ex:
"#{:abc}"
---> "abc"

2008年5月25日 星期日

methods

methods:
A.methods:
show class methods
A.methods(false):
only show class methods of A, not including inherited methods
a.methods:
show instance methods of a

instance_methods:
A.instance_methods equals a.methods
A.instance_methods(false):
show only instance_methods 0f A, not including inherited methods

private_methods, public_methods, protected_methods, singleton_methods



compare: equal?, Comparable module

check  whether  two objects are the same object

define how to compare
use Comparable module & define <=> method
the return value of method <=> ,  1, 0 , & -1 decides greater than, equal than, & less than
ex:
class Rabbit
     include Comparable 
     attr_accessor  :name

     def  <=> (other_rabbit)
          if  self.name <>
                  -1
          elsif  self.name > other_rabbit.name
                  1
          else
                  0
          end 
     end
end

if the thing to compare know how to compare, there is a shorter definition
ex:
def  <=> (other_rabbit)
       self.name<=> other_rabbit.name
end


true, false & nil

In Ruby, nil & false  are the only two objects have boolean value of false

2008年5月24日 星期六

for, each

for
ex:
for a in [1,2,3]
puts a
end

each
ex:
[1,2,3].each do |i|
puts i
end

loop, while, until

loop
ex:
loop do
    a=a+1
    break if a>3
end

loop do 
     a=a+1
     next if a <3
     break
end

while
ex:
while a<3
end

until:
ex:
until a>3
end



case

ex:
case  name
when "peter"
puts "peter"
when "andy"
puts  "andy"
else
puts  "others"
end

how it works
translate to 
if "peter" === name

note: the === method can be customarily defined