Ruby语法基础(二)

Ruby语法基础(二)

继续ruby的学习,这次主要把目光放到运算符,条件判断,循环,方法,以及其他ruby特有的基本概念上

运算符

  • 算术运算符:+,-,/,%,**,值的注意的是,ruby中一切皆为对象,a+b等价于a.+(b)
  • 比较运算符:基本与Python的一致,不等于要用!=,还有联合运算符<=>,返回-1,0,1。.eql?判断数据值是否相等以及数据类型是否相等。equal?判断两个对象的id是否相等
  • 赋值运算:与Python一致,可以用a, b, c = 10, 20, 30并行赋值,交换也可以直接运行
  • 位运算:与Python一致,对二进制位操作,支持&, |,^,~(取反),<<,>>
  • 三元运算符: ? :
  • 范围运算符: 两个.包含结尾位置1..3(1,2,3);三个点不包括结尾1…3(1,2)
  • defined?:判断是否已经定义
foo = 42; $VAR = 1
# 1.判断变量是否已经初始化
puts defined? foo # local-variable
puts defined? $VAR # global-variable
puts defined? bar # 未定义
# 2.判断方法是否已经定义
puts defined? puts # method

条件判断

if…else

x = 1
if x>2
  puts 'x > 2'
elsif x<=2 and x!=0
  puts 'x = 1'
else
  puts 'unknow x'
end

if修饰词

if后的条件成立才执行前面一句(比较灵活的写法)

a = 1
print a if a # 变量a被定义过了,所以返回true

unless

与if刚好相反

case

age = 5
case age
  when 0..2
    puts '婴儿'
  when 3..6
    puts '小孩'
  when 7..12
    puts '少年'
  else
    puts '其他'
end

循环

while

i = 0; num = 5
while i<num
  puts i; i += 1
end

while修饰符

i = 0; num = 5
begin
  puts i; i += 1
end while i<num

until

until与while完全相反

for

for i in 0..5
  if i == 2
    next # 相当于continue
  elsif i == 4
    break # 跳出循环
  end
  puts i
end

方法

  • 方法名必须以小写开头,否则会被当成常量
  • Ruby 中的每个方法默认都会返回一个值。这个返回的值是最后一个语句的值
  • return 语句用于从显示从方法中返回一个或多个值
def test(a=1, b) # 可以使用默认参数
  return a+b, a-b
end
sum, sub = test 2, 3
puts sum, sub
  • 不定长参数
def sample (*test) # *号允许可变数量的参数
  test.each do
    |item|
    puts item
  end
end
sample 'a', 'b'
sample 1, 2, 3
  • 类方法

class Accounts
   def reading_charge
     # dosomething
   end
   def Accounts.return_date
     # 类方法
   end
end
Accounts.return_date # 类方法调用
  • alias可以重命名
alias 方法名 方法名
alias 全局变量 全局变量
  • undef取消定义
undef 方法名

块在ruby中用{}包裹,也可以用do end形式

# 定义函数
def myloop
  while true
    yield
  end
end

num = 1
# 执行myloop函数时,会把块中内容挂载到yield处
myloop do
  puts "num is #{num}"
  break if num > 100
  num *= 2
end
# 运行结果
num is 1
num is 2
num is 4
num is 8
num is 16
num is 32
num is 64
num is 128

传递参数

def total(from, to)
  result = 0
  from.upto(to) {
      |num|
    if block_given?
      result += yield num
    else
      result += num
    end
  }
  result
end
puts total 1, 3
puts total(1,3) { # total后一定要紧跟括号
    |num|
  num ** 2
}

块本身也可以作为参数传递给函数(不实用yield方法)

# 块本身也可以作为参数传递给函数
def test(&block)
  block.call
end

test {
  puts 'Hello World!'
}

模块

模块可以把方法、常量、模块组合在一起

  • 模块提供了一个命名空间,避免了名字冲突
  • 模块实现了mixin装置
  • 模块不能实例化
  • 模块没有子类
  • 模块只能被另一个模块定义

被引用的模块文件support.rb

module Support
  PI = 3.1415926
  def Support.hello(name) # 模块中的普通函数用模块名开头区分
    puts "hello #{name}"
  end
end

module Week
  FIRST_DAY = 'Sunday'
  def Week.weeks_in_month
    puts 'You have 4 weeks in a month'
  end

  def Week.weeks_in_year
    puts 'You have 52 weeks in a year'
  end
end

main.rb

$LOAD_PATH << '.' # 添加搜索路径目录
require 'support' # 添加具体模块

# 调用模块方法
Support::hello 'ruby'
# 读取模块函数
puts Support::PI

# 在类中引用模块内容要用include
class Decade
  def initialize
    @no_of_yrs = 10
  end
  # include Week
  def no_of_months
    puts Week::FIRST_DAY
    number = @no_of_yrs * 12
    puts number
  end
end

d = Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year
d.no_of_months

#运算结果
hello ruby
3.1415926
Sunday
You have 4 weeks in a month
You have 52 weeks in a year
Sunday
120

mixins实现多重继承

support.rb

module A
  def a1
    puts 'a1'
  end
  def a2
    puts 'a2'
  end
end

module B
  def b1
    puts 'b1'
  end
  def b2
    puts 'b2'
  end
end

main.rb

$LOAD_PATH << '.' # 添加搜索路径目录
require 'support' # 添加具体模块

class Sample
  # 用 include方法把模块中的方法包含到类内
  # 组装模块
  include A
  include B
  def s
    puts 's'
  end
end

s = Sample.new
s.a1 # 调用模块中的方法
s.a2
s.b1
s.b2
s.s
原文地址:https://www.cnblogs.com/fanghao/p/7865635.html