博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Ruby小例子
阅读量:7078 次
发布时间:2019-06-28

本文共 1235 字,大约阅读时间需要 4 分钟。

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

def fact(n)  if n == 0   1  else   n * fact(n-1)  end endprint 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 enddogobj = Dog.new dogobj.speak

 

结果: Bow Wow

6.继承 #注释

class Dog    def speak        print "Bow Wow\n"    endendclass SpottyDog

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

class Dog    def speak        print "Bow Wow\n"    endendclass RobotDog

 

结果: 会报错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.identifyclass Student1

 

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

转载地址:http://gsdml.baihongyu.com/

你可能感兴趣的文章
09网易校园招聘笔试题
查看>>
。一个通俗易懂的HMM例子
查看>>
freeswitch 挂断前执行脚本
查看>>
EffectManager
查看>>
python packages prebuild for windows
查看>>
这样就算会了PHP么?-10
查看>>
远程调用WMI安装软件
查看>>
从零开始学习jQuery (七) jQuery动画-让页面动起来!
查看>>
asp.net 操作word
查看>>
SQL Server 权限管理
查看>>
郎意难坚,侬情自热(文/王路)
查看>>
Form_Form Builder开发基于视图页面和自动代码生成包(案例)
查看>>
Android SDK Manager 中如果没有相应的镜像ARM XX Image
查看>>
简单聊下Unicode和UTF-8
查看>>
ASP.NET Web API的Controller是如何被创建的?
查看>>
在 Azure 上使用 Docker运行 Mono
查看>>
(转)JITComplier、NGen.exe及.NET Native
查看>>
Ant build xml中的各种变量解释
查看>>
labview视频采集IMAdx
查看>>
Android:实现一种浮动选择菜单的效果
查看>>