• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Ruby小例子

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
一步一步学Ruby(十四): self和作用域发布时间:2022-07-14
下一篇:
Ubuntu 10.10下搭建Ruby on Rails 2.3.5开发环境发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap