zoukankan      html  css  js  c++  java
  • Ruby

    1.函数

    def sayHello(name="Levi")
        puts "hello #{name}."
    end
    
    sayHello

    结果如下

     2.类

    class Player
        def initialize(name="levi")#构造函数
            @name=name
        end
        def show()
            puts "player:#{@name}"
        end
    end
    
    levi=Player.new()
    levi.show()
    
    curry=Player.new("curry")
    curry.show()
    
    harden=Player.new("harden")
    harden.show()

    结果如下:

     3.类的instance_methods()方法,ture表示输出他的实例方法,false输出所有的方法

      对象的respond_to?() 方法,表示对象是否含有这个参数签名的方法

      对象的send()方法,表示执行这个方法

    class Game
        def initialize(title="怪物猎人",price=200)
            @title=title
            @price=price
        end
        def show()
            puts "标题:#{@title}"
            puts "价格:#{@price}"
        end
        def show2()
        end
        def show3()
        end 
    end
    
    puts Game.instance_methods(false)
    
    mario=Game.new("超级马里奥",360);
    if mario.respond_to?("show")
        mario.send("show")
    end

    4.类的属性:

    class Game
        attr_accessor:price ,:title
        def initialize(title="怪物猎人设计",price=200)
            @title=title
            @price=price
        end
        def show()
            puts "标题: #{@title}"
            puts "价格: #{@price}"
        end 
    end
    
    mygame=Game.new()
    mygame.show()
    
    puts "title is "+mygame.respond_to?("title").to_s
    puts  "price is"+mygame.respond_to?("price").to_s 
    
    mygame.price=150
    mygame.show()

    输出如下

     5.数组

    games=["绝地逃生","怪物猎人世界","LOL"]
    games.each do |game|
        puts "我爱<<#{game}>>"
    end
    
    games.each_with_index do |game,i|
        puts "#{i}.#{game}"
    end
    
    puts games.join(",")
    
    if games.respond_to?("each")##respond_to用来判断是不是有each这个方法
    end

    输出如下:

  • 相关阅读:
    不兼容结构的协调—适配器模式(三)
    Java的时间空间复杂度详解
    Java学习笔记之变量和类变量的访问哲学
    求最大公约数-辗转相除法
    java中怎么遍历HashMap
    Java编程时如何节省内存,效率高
    Java入门需掌握的30个基本概念
    Java各种获取系统当前时间方法和格式
    Java 实现顺序结构线性列表
    Java编程中异常处理的优劣之道
  • 原文地址:https://www.cnblogs.com/1521681359qqcom/p/12523732.html
Copyright © 2011-2022 走看看