zoukankan      html  css  js  c++  java
  • Ruby初见

    一. 简介

    Ruby,一种简单快捷的面向对象(面向对象程序设计)脚本语言,在20世纪90年代由日本人松本行弘(Yukihiro Matsumoto)开发,遵守GPL协议和Ruby License。

    二. 官方社区(中文)

    https://ruby-china.org/

    三. 安装

    ruby下载安装:https://www.ruby-lang.org/zh_cn/documentation/

    rvm下载安装:https://ruby-china.org/wiki/rvm-guide

    四. 初试

    # 万变不离其宗,先来一个hello world
    puts "Hellow world"

    五. 函数

    def sayHello
      puts "Hello world"
    end
    sayHello
    
    def sayHello1(name)
      puts "Hello #{name}"
    end
    sayHello1("ruby")

    ruby的函数传参与Python类似,需注意的就是占位输出"#{}"

    六.类

    class Player
      def initialize(name = "python")  # 构造函数
          @name = name
      end
    
      def show()
        puts "player: #{@name}"
      end
    end
    
    python = Player.new()
    python.show()
    
    ruby = Player.new("ruby")
    ruby.show()
    
    go = Player.new("go")
    go.show()
    Ruby 支持五种类型的变量。
    1. 一般小写字母、下划线开头:变量(Variable)。
    2. $开头:全局变量(Global variable)。
    3. @开头:实例变量(Instance variable)。
    4. @@开头:类变量(Class variable)类变量被共享在整个继承链中
    5. 大写字母开头:常数(Constant)。

    1. 先熟悉三个方法

    instance_methods(all:bool):列出对象(类)内部的方法
    respond_to?:调查对象的方法/属性是否可用
    send:执行对象的方法

    (1). instance_methods:列出对象(类)内部的可用方法,用于调查解析对象的使用。

    class Game
      def initialize(title="怪物猎人", price = 200)
        @title = title
        @price = price
      end
    
      def show()
        puts "标题: #{@title}"
        puts "价格: #{@price}"
      end
    
      def show_1()
      end
    
      def show_2()
      end
    end
    
    puts Game.instance_methods(false )

     注:可以试试把instance_methods中的false改成true

    (2). respond_to?:调查对象的方法/属性是否可用,send:执行对象的方法

    ...
    mario = Game.new("超级马里奥", 350)
    if mario.respond_to?("show")  # 判断对象是否存在show方法
      mario.send("show")          # 执行指定的方法
    end

    2. attr_accessor:定义可存取对象的属性

    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.title = "Super Mario World"
    mygame.price = 150
    mygame.show

    注:感觉有点像Python中的global,用来定义全局变量

    。。。

    先到这,稍后继续

  • 相关阅读:
    javascript keycode大全
    在WEB环境下打印报表的crystal的解决方案
    Trim()
    C#应用结构体变量
    锚点定位
    C# 按地址传值
    [GIIS]JS 图片 Preview
    c# 模拟网站登陆
    此数据库没有有效所有者,因此无法安装数据库关系图支持对象" 解决方法
    风讯.NET与NETCMS的选择—开源.NET内容管理系统
  • 原文地址:https://www.cnblogs.com/rixian/p/11634601.html
Copyright © 2011-2022 走看看