《Rubu基础教程第五版》第九章笔记 运算符

赋值运算符

+= -+这种,跟Python基本一样的操作

 

逻辑远算符的应用

首先这里有着很多编程语言独有的短路原则,这个不讲了

概念上一下

表达式的执行顺序是从左到右

如果逻辑表达式的真假已经可以确定,则不会在判断剩余的表达式(短路原则)

最后一个表达式的值为整体逻辑表达式的值

 

item = arry && arr.first

还有一种写法为 item = arr&.first 中间没有空格

这个叫做安全运算符,或nil检查方法调用,arry不是nil或者false item的arr.first

 

var ||= 1

var = var || 1, 这个也非常由意思,是一个nil 或者 false给予默认值的写法,var由值的化,就不会进行赋值

 

条件运算符,Python中的三元表达式

条件 ? 成立的表达式: 不成立的表达式

a = 1

b = 2

max =  a > b ? a : b

python的写法 max = a if a > b else b

 

范围运算符

可以用过Range.new

irb(main):015:0> Range.new(1,5).each {|n| p n}
1
2
3
4
5
=> 1..5

 首位都可以取到,跟Python完全不一样

也可以用过(1..5)或者(1...5)多一个点表示尾部的数字取不到

通过to_a的方式,可以将range转换成array

irb(main):016:0> (1..3).to_a
=> [1, 2, 3]
irb(main):017:0> (1...3).to_a
=> [1, 2]
irb(main):018:0> 

 还可以定义字符串的列表

irb(main):018:0> ("A".."D").to_a
=> ["A", "B", "C", "D"]
irb(main):019:0> ("A"..."D").to_a
=> ["A", "B", "C"]
irb(main):020:0> 

 

对象通过succ的方法,可以根据起点逐个生成接下来的值

irb(main):020:0> val = "a"
=> "a"
irb(main):021:0> val = val.succ
=> "b"
irb(main):022:0> val = val.succ
=> "c"
irb(main):023:0> val = val.succ
=> "d"
irb(main):024:0> val = val.succ
=> "e"
irb(main):025:0> 

 

远算符优先级

 

定义运算符,很多是不能定义的

上能定义的二元远算符

class Point
  attr_accessor :x, :y  # 定义存储器,可以对该属性进行读取,赋值

  def initialize(x=0.0,y=0.0)
    @x, @y = x, y
  end
  
  def inspect   # 相当于Python中__repr__
    "(#{x}, #{y})"
  end

  def +(other)
    self.class.new(x + other.x, y + other.y)
  end
  
  def -(other)
    self.class.new(x - other.x, y - other.y)
  end
  

  def swap(other)
    tem_x, tem_y = @x, @y
    @x, @y = other.x, other.y
    other.x, other.y = tem_x, tem_y  # 在同一个类中调用protected方法
    self
  end
end

p0 = Point.new
p1 = Point.new(1.0, 2.0)

p [p0.x, p0.y]
p [p1.x, p1.y]

p p0 - p1
p p0 + p1

 

每个对象都由to_s与inspect的方法默认,相当与Python的str与erpr函数的调用

 

一元运算符 +- ~!分别以+@、-@,~@、!@为方法来定义

这个不写了

 

定义下标方法 相当于Python中的__getitem__与__setitem__

class Point
  attr_accessor :x, :y  # 定义存储器,可以对该属性进行读取,赋值

  def initialize(x=0.0,y=0.0)
    @x, @y = x, y
  end
  
  def inspect   # 相当于Python中__repr__
    "(#{x}, #{y})"
  end

  def +(other)
    self.class.new(x + other.x, y + other.y)
  end
  
  def -(other)
    self.class.new(x - other.x, y - other.y)
  end
  
  def [](index)  # 读操作
    case index
    when 0
      x
    when 1
      y
    else
      raise ArgumentError, "out of range '#{index}'"
    end
  end

  def []=(index, value)
    case index
    when 0
    self.x = value
    when 1
    self.y = value
   else
     raise ArgumentError, "out of range '#{index}'"
   end
  end


  def swap(other)
    tem_x, tem_y = @x, @y
    @x, @y = other.x, other.y
    other.x, other.y = tem_x, tem_y  # 在同一个类中调用protected方法
    self
  end
end

p0 = Point.new
p1 = Point.new(1.0, 2.0)

p [p0.x, p0.y]
p [p1.x, p1.y]

p p0 - p1
p p0 + p1


p p0[0]
p p0[1] = 3
p p0[1]
p p0[2]

 

方法的定义,Ruby好多了,不用取记很多Python中的所谓的魔法方法

 

posted @ 2020-06-01 00:55  就是想学习  阅读(166)  评论(0编辑  收藏  举报