Ruby小例子

1.ruby定义函数与执行函数案例

def fact(n)  if n == 0   1  else   n * fact(n-1)  end end

print fact(4)

 

结果: 24

2.一个小例子

words = ['a','b','c'] secret = words[rand(3)] print "guess?\n" while guess = STDIN.gets  guess.chop!  if guess==secret   print "You win!\n"   break  else   print "Sorry,you lose.\n"  end  print "guess?\n" end print "The word was ",secret,"\n"

 

结果: guess? a Sorry,you lose. guess? b You win! The word was b

3.流程控制 #注释

def checknum(i) case i when 1..5  print "1..5\n" when 6..10  print "6..10\n" end end checknum(8)

 

结果: 6..10

4.for循环 #注释

def loopnum(a,z)  for num in("#{a}".."#{z}")   print num,"\n"  end end loopnum(1,9)

 

结果: 1 2 3 4 5 6 7 8 9

5.类的演示 #注释

class Dog  def speak   print "Bow Wow\n"  end end

dogobj = Dog.new dogobj.speak

 

结果: Bow Wow

6.继承 #注释

class Dog
    def speak
        print "Bow Wow\n"
    end
end

class SpottyDog<Dog
    def wash
        print "Wash my spotty\n"
    end
end


spotty = SpottyDog.new
spotty.speak
spotty.wash
结果:
Bow Wow
Wash my spotty

可以砍掉一些不需要的方法

class Dog
    def speak
        print "Bow Wow\n"
    end
end


class RobotDog<Dog
    def speak
        fail "Sorry.I cant speak"
    end
end


robot = RobotDog.new
robot.speak

 

结果: 会报错Sorry.I cant speak

7.重载方法 #注释

class Human  def identify   print "I'm a person.\n"  end  def train_toll(age)   if age<12    print "Reduced fare.\n"   else    print "Normal fare.\n"   end  end end Human.new.identify

class Student1<Human  def identify   print "I'm a student.\n"  end end Student1.new.identify

class Student2<Human  def identify   super   print "I'm a student.\n"  end end Student2.new.identify

class Dishonest<Human  def train_toll(age)   super(11)#不诚实的孩子  end end Dishonest.new.train_toll(25)

class Honest<Human  def train_toll(age)   super(age)#不诚实的孩子  end end Honest.new.train_toll(25)

 

结果: I'm a person. I'm a student I'm a person. I'm a student Reduced fare. Normal fare.

posted @ 2014-01-12 23:08  TBHacker  阅读(383)  评论(0编辑  收藏  举报