首页 > 代码库 > 关于Ruby常用语法案例累积

关于Ruby常用语法案例累积

变量问题:

类变量和方法变量的区别是什么?

类变量:可以直接使用

方法变量:需要实例化后,才能使用该变量

案例一:

class Person   @@name = "Tom"    @@names = "Toms"    @@age = 10    def jek      @jj = "jj"      @@bb="wonter"  end    def Person.getName    return  @@name  end  def Person.getNames      return  @@names    end      def Person.getage        return  @@age        end    endclass Xx < Person    def aa        puts "#{@@age}"            ll = Person.new        ll.jek        @bb = @@bb        puts "#{@bb}"            endendputs Person.getNamesx = Xx.newx.aa

父子类继承问题:

重写父类方法,或直接使用父类方法。

案例二:

class Father  def says    puts "I am father."  end  def fatherInfo    puts "father info."  endendclass Son < Father    def sonInfo    puts "son info."    endendclass Two < Father    def twoInfo    puts "two info."    endend#father = Father.newson = Son.newtwo = Two.new#father.says#father.fatherInfoson.saysson.sonInfoson.fatherInfotwo.twoInfotwo.says

传参问题:

类之间参数的传递与使用。

案例三:

class Father  def initialize name    @name = name  end  def says    puts "I am father."  end  def fat xx      @xname = xx      puts "I am father. #{@xname}"  end  endclass Son < Father  def sayss    puts "I am son. name: #{@name}"  end  def sonsays      puts "no : #{@name}"  end  endson = Son.new "Tom"#son.says#son.sonsaysson.fat "wonter"

循环和判断问题:

涉及数组

案例四:

list1 = ["192.168.48.202","icare","log"]list2 = ["192.168.48.101","tomcat","sysif"]length = list1.lengthlength.times do |t|   #print "#{list2[t]} \n"    if list2[t] = list1[t]     puts "ok list1:#{list1[t]} \n list2:#{list2[t]}" else     puts "no" endend  puts "#################################################################"for i in list1 do    print "#{i} "  end puts "\n"

关于引入与通配:

load D:\Workspaces\Ruby2\control\CdkPkg.rb#load ‘D:\Workspaces\Ruby2\control\Cdel_linkP.rb‘class Home   def test_linkpkg          pkg=ClinkPkg.new      pkg.linkPkg   end#  def test_del_linkP#      del=Cdel_linkP.new#      del.del_linkP#   endendt = Home.newtest_methods = t.public_methods.grep(/^test_/)  # 把所有test_开头的方法找出来。test_methods.each do |test|  t.send(test)  # 执行每个测试用例。end

其实不管什么语言,什么语法都是大同小异,关键就看怎么用的好,怎么用的顺手。

 

关于Ruby常用语法案例累积