Ruby小例子

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

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

print fact()

结果: 24

2.一个小例子

words = ['a','b','c'] secret = words[rand()] 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 ..  print "1..5\n" when ..  print "6..10\n" end end checknum()

结果: 6..10

4.for循环 #注释

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

结果: 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<    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()#不诚实的孩子  end end Dishonest.new.train_toll()

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

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

上一篇:OpenCV_contrib里的Text(自然场景图像中的文本检测与识别)


下一篇:android HTTPclient