ruby 快速学习

说明:
1. [xxx] 表示语法可省略
2. (物件导向) 所有的函数调用,都是用 “.” 来调用,不会出现 python或JS类的 parseInt(n)/int(n) 这样的写法,只有 n.to_s

基础

中文问题

遇到中文: 必须在首行添加下面代码

# -*- coding: UTF-8 -*- # 必须在首行

注释问题

# -*- coding: UTF-8 -*- # 必须在首行
# 这是单行注释

=begin
这是多行注释;
这是多行注释;
=end

定义函数

define xxx
 ...
end

输出

puts: 可换行

print: 单行输出不换行,多行输出作为字符串块

echo: (执行函数)

puts 'xxx'

空白问题

a + b 被解释为 a+b (这是一个局部变量)
a +b 被解释为 a(+b) (这是一个方法调用)

保留关键字

BEGIN do next then
END else nil true
alias elsif not undef
and end or unless
begin ensure redo until
break false rescue when
case for retry while
class if return while
def in self FILE
defined? module super LINE

字符串的集中表达方式

# -*- coding: UTF-8 -*-
print <<EOF 
    aa
    bb
EOF
print '---'  #不会换行
print <<'EOF'
    aa
    bb
EOF
puts '执行命令'
print <<`hehe` # 此处要注意,必须有一个 "<<"
    echo 你好  #  ``该执行符号 得 配合 echo  一起使用
hehe

puts '多个命令'
print <<hehe,<<haha  #该处的"<<"后不能有空格,变量紧跟"<<"
    呵呵   
hehe
    哈哈
haha

程序执行前后操作

BEGIN 和 END 属于块级函数,一个程序可有多个块级程序

BEGIN 程序在程序运行前调用,即初始化程序;

BEGIN {
    puts 'want to do,starting...'
}

END 程序在程序退出前调用

END{
    puts 'want to do,ending...'
}

引号问题

和其他语言一样,单双引号互用

变量在字符串内的展示

name = 'ruby'
puts name
puts "this is #{name}" # 着重:此处必须双引号,否则不能解析变量

数组及遍历

1.数组遍历

#第一种
arr = [ "fred", 10, 3.14, "This is a string", "last element", ]
arr.each do |i|
    puts i 
end
# 第二种
(5..9).each do |d|
    puts d,'--->'
end

输出数组

arr = Array.new(10)
puts "#{arr}"

2.新建数组

# -*- coding: UTF-8 -*- # 必须在首行

#new()
arr = Array.new(20)
puts "#{arr}" 
=begin
特别奇怪??? 为什么输出的是 ['nil',...]????
难道是建立一个空的数组位置,但没有赋值
=end

#范围内创建数组
(5..9).each do {|d| puts "#{d}"}
arr = Array(5...9)
puts arr.size
puts "#{arr}"
#.[]()
arr = Array.[](1,2,3,4)  #有点函数
#[]
arr = Array[1,2,3,4]    #直接赋值
#每个元素赋同样的值
arr = Array.new(4,'都一样') 
puts "#{arr}"
#lambda 表达式
arr = Array.new(10){|e| e = e*2}
puts arr.size

3.数组属性

arr = Array.new(20)

puts arr.size
puts arr.length

索引数组值

arr = Array(5,9);
puts "#{arra.at(6)}"

类型转换

string 类型转换

a = '1'
a.to_s  # 字符串
a.to_f  # 浮点型
a.to_i  # 整数

字串符号Symbols

Symbol是唯一且不会变动的识别名称,用冒号开头:

:this_is_a_symbol
为什么不就用字串呢?这是因为相同名称的Symbol不会再重复建构物件,所以使用Symbol可以执行的更有效率。范例如下:

puts "foobar".object_id      # 输出 2151854740
puts "foobar".object_id      # 输出 2151830100
puts :foobar.object_id       # 输出 577768
puts :foobar.object_id       # 输出 577768

类名、函数名 首字母必须大写

类 Class

类名首字母必须大写

Class Abc{  # 首字母大写
    Number a     
    Characters b

}

类里面可以定义子类:重点是必须有结束语 end `

class Abc{
    # 定义子类
    class Abc_sub  # 首字母还是必须大写
        ...
    end    
    # 必须有结束符号 end
    # 必须有结束符号 end
    # 必须有结束符号 end
}
  • 局部变量局部变量是在方法中定义的变量。局部变量在方法外是不可用的。在后续的章节中,您将看到有关方法的更多细节。局部变量以 小写字母_ 开始。

  • 实例变量实例变量可以跨任何特定的实例或对象中的方法使用。这意味着,实例变量可以从对象到对象的改变。实例变量在变量名之前放置符号 (@)

  • 类变量类变量可以跨不同的对象使用,但,不能跨类使用。类变量属于类,且是类的一个属性。类变量在变量名之前放置符号 (@@)

  • 全局变量可以跨类使用。如果您想要有一个可以跨类使用的变量,您需要定义全局变量。全局变量总是以美元符号 ($) 开始。

类函数 def

??? Function 是什么东西?

# -*- coding: UTF-8 -*- # 必须在首行
Class Abc{              # 首字母大写
    Number a     
    Characters b
    # ??? 这是啥鬼???
    Function aa{        # 首字母大写
        puts 'aa 函数'
    }
    Function bb{        # 首字母大写
        puts 'bb 函数'
    }

    def aa
        puts 'hello'
    end
}

类创建对象

new 方法属于类方法

object1= Abc. new 

初始化函数

将在调用带参数的类的 new 方法时执行

class Abc
    @@static_var = 0;   # 类变量
    def initialize(a,b,c)
    @a = a   # 实例变量
    @b = b 
    @c = c
# 实例化
class Abc.new('a','b','c')

样例

# -*- coding: UTF-8 -*- # 必须在首行
# 无参数的实例方式
class Abc
    def hi
        puts 'hi,i\'m yeSir'
    end
end
# 实例化对象
object = Abc. new  
object.hi # hi,i'm yeSir



# 有参数的实例方式
# TODO
class Abc
    @@classVar=0
    def initalize(f,s,t)
        @f = f;
        @s = s;
        @t = t;
    end

    def display_args()
        puts "display_args() classVar is: #@@classVar"
        puts "first aguments #@f"
        puts "second aguments #@s"
        puts "third aguments #@t"

    end

    def testClassVar()
        @@classVar += 1;
        puts "classVar is #@@classVar"
    end
end
obj1 = Abc.new('a','b','c')
obj2 = Abc.new('d','e','f')

obj2.testClassVar
obj1.testClassVar


obj1.display_args
obj1.display_args

条件判断

if 循环

常规写法

# -*- coding: UTF-8 -*-
if condition 
    code
elsif condition
    code
else
    code

简写形式

if condition then code end;
code if condition

unless(if相反)

condition 为假时,执行code

unless condition [then]
    code
else
    code
end

简洁写法

code unless condition

case 语句

# -*- coding: UTF-8 -*-
case expression
when condition
    code
when condition
    code
else 
    code
end

简洁的写法

case   # 此处没有条件
when true then code 
when false then code
when true then code
end

# 例子
case 
when false then puts 'no'
when true then puts 'yes'
when true then puts 'no2'
end

while 语句

while condition [do或:]
    code
end

简写形式

code while condition
# 或者   该语句可以在 while 判断之前先执行一次 begin 内的函数;
begin 
    code
end while condition

until 语句

while 的相反语句
condition 为假时,执行code

until condition [do]
    code
end

函数

必须使用小写字母开头,如果以大写字母开头,会被解析成变量;
必须调用之前,就申明一个函数,否则会报错;

函数参数不定,枚举

# -*- coding: UTF-8 -*- # 必须在首行
def sample (*test)
   puts "参数个数为 #{test.length}"
   for i in 0...test.length
      puts "参数值为 #{test[i]}"
   end
end
sample "Zara", "6", "F"
sample "Mac", "36", "M", "MCA"

函数的一般调用

# -*- coding: UTF-8 -*- # 必须在首行
def test(a=1,b=2)
    puts a+b;
end

# 调用函数
test a b

函数返回

# -*- coding: UTF-8 -*- # 必须在首行
def test
   i = 100
   j = 200
   k = 300
return i, j, k
end
var = test
puts var

类方法

类方法,内部默认是 public,定义在类的外部,默认是 private

可以通过 Module 的 private 和 public 来改变类方法的默认标记

不声明,访问类方法

class Accounts
   def reading_charge
        code
   end
   def Accounts.return_date
        code
   end
end
# 调用
Accounts.return_date
# #########

私有类和共有类改变

class MyClass

  def public_method
  end

  private

  def private_method_1
  end

  def private_method_2
  end

  protected

  def protected_method
  end

end

类的继承

class Pet
  attr_accessor :name, :age

  def say(word)
    puts "Say: #{word}"
  end
end

class Cat < Pet
  def say(word)
    puts "Meow~"
    super
  end
end

class Dog < Pet
  def say(word, person)
    puts "Bark at #{person}!"
    super(word)
  end
end

Cat.new.say("Hi")
Dog.new.say("Hi", "ihower")

# 输出

Meow~
Say: Hi
Bark at ihower!
Say: Hi

undef 取消方法定义

undef 方法名

函数 TODO …

常规使用的块

# -*- coding: UTF-8 -*-

def test
   puts "a"
   yield
   puts "b"
   yield
end
test {puts "c"}  #result : a c b c

单个块调试

# 单个块调试、调用
blockTest = lambda {
    puts '单纯的一个block'
}
# 调用
blockTest.call()

给块传参

def test
   yield 5
   puts "在 test 方法内"
   yield 100
end
test {|i| puts "你在块 #{i} 内"}

函数 + 块

块名作为参数,放到最后一个参数,以 &参数 传入
def test(&a)
    a.call  # 块调用
    puts '最后调用'
end
test { puts "Hello World!"}

模块

定义模块

  • 常量 首字母大写
  • 函数 模块名后加点,再接一个函数
# test.rb
module Trig  # Trig 是模块名
   PI = 3.141592654 # 常量 首字母大写
   def Trig.sin(x)  # 函数定义,模块.函数
   # ..
   end
   def Trig.cos(x)  # 函数定义,模块.函数
   # ..
   end
end

引入模块

  • 模块引入 : require 文件名
  • 常量 : 以 双冒号 引入 (::常量名)
  • 方法 : 以 点 引入 (.函数名)
  • 类里引入 : 在类里面可以 include 引入
require test[.rb]
a = Trig.sin(Trig::PI/4)   # 模块函数


class Test
include Trig  # 引入模块
def test 
    puts Trig::PI
end
#调用
dd = Test.new
dd.test

参考文章:

菜鸟教程:http://www.runoob.com/ruby/ruby-tutorial.html
ruby 快速入门:https://ihower.tw/rails/ruby-cn.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章