zoukankan      html  css  js  c++  java
  • 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?
    " while guess = STDIN.gets  guess.chop!  if guess==secret   print "You win!
    "   break  else   print "Sorry,you lose.
    "  end  print "guess?
    " end print "The word was ",secret,"
    "

    结果: 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
    " when 6..10  print "6..10
    " end end checknum(8)

    结果: 6..10

    4.for循环 #注释

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

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

    5.类的演示 #注释

    class Dog  def speak   print "Bow Wow
    "  end end
    
    dogobj = Dog.new dogobj.speak

    结果: Bow Wow

    6.继承 #注释

    class Dog
        def speak
            print "Bow Wow
    "
        end
    end
    
    class SpottyDog<Dog
        def wash
            print "Wash my spotty
    "
        end
    end
    
    
    spotty = SpottyDog.new
    spotty.speak
    spotty.wash
    结果:
    Bow Wow
    Wash my spotty

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

    class Dog
        def speak
            print "Bow Wow
    "
        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.
    "  end  def train_toll(age)   if age<12    print "Reduced fare.
    "   else    print "Normal fare.
    "   end  end end Human.new.identify
    
    class Student1<Human  def identify   print "I'm a student.
    "  end end Student1.new.identify
    
    class Student2<Human  def identify   super   print "I'm a student.
    "  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.

  • 相关阅读:
    es6语法快速上手(转载)
    width百分比
    利用switch case 来运行咱们结婚吧
    利用if else来运行咱们结婚吧
    利用if else 来计算车费
    利用switch case判断是今天的第多少天
    利用if else判断是否及格
    利用if,else判断输入的是不是一个正整数
    再练一遍猜拳
    用if else 判断是不是7的倍数等
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/3516699.html
Copyright © 2011-2022 走看看