zoukankan      html  css  js  c++  java
  • 读<<programming ruby>> 7.6节 flip-flop 理解

    书中源码是这样的

    File.foreach('1.txt') do |x|
      if(($. == 1) || x =~ /eig/) .. (($. == 3) || x =~ /nin/) then
        print x
      end
    end

    其中 1.txt内容如下

    first
    second
    third
    fourth
    fifth
    sixth
    seventh
    eigth
    ninth
    tenth

    按道理 读取第一行的first,$.应该是1 ($.是一个全局变量,表示行号)但是rubymine调式发现不是1,这个我暂时没找到原因。所以经别人提示。我改成这样

    f = File.new('1.txt')
    f.each do |line|
      if ((f.lineno == 1) || line.chomp =~ /eig/)..((f.lineno== 3) || line.chomp =~ /nin/) then
    
    
    
        print f.lineno
        print line
      end
    end
    

      

    这样 f.lineno表示每次读取的行号 运行测试结果如下

    书上只提到2点,

    1 exp1..expr2这样的rang, 在exp1变为真之前,它的值为假,在exp2变为真正之前,rang被求解为真
    2 这段代码片段。就是打印1到3行及位于/eig/和/nin/之间

    有点晦涩难懂,然后群里有人提示,看这个文章: http://nithinbekal.com/posts/ruby-flip-flop/

    The flip flop operator is a range (..) operator used between two conditions in a conditional statement. It looks like this:

    (1..20).each do |x|
      puts x if (x == 5) .. (x == 10)
    end
    

     The condition evaluates to false every time it is evaluated until the first part evaluates to true. Then it evaluates to true until the second part evaluates to true. In the above example, the flip-flop is turned on when x == 5 and stays on until x == 10, so the numbers from 5 to 10 are printed.

    (x == 5) .. (x == 10) 这个东西叫做flip flop 

    
    
    1 蓝色英文就是说,当第一部分也就是(x==5)为真的时候。整个if判断为真,但是什么时候为假呢。直到第二部分为真也就是(x==10)时候,
      也就是前面提到的 exp1..expr2这样的rang, 在exp1变为真之前,它的值为假,在exp2变为真正之前,rang被求解为真
    2  红字英文意思就是 x==5时,这个表达式开始执行。什么时候停止呢,知道x==10,所以打印5到10之间
    

      

    所以理解 

    ((f.lineno == 1) || line.chomp =~ /eig/)..((f.lineno== 3) || line.chomp =~ /nin/)

    可以这么想,当f.lineno 值为1的时候 这个表达式 ((f.lineno == 1) || line.chomp =~ /eig/) 为真,整个if 为真,

    然后打印 1first,什么时候打印终止?,当flineno=3或者line.chomp(chomp去掉行尾的/r/n)的值匹配/nin/,他们两个满足其中一个的时候 就不打印了。

    可以像下面代码这样理解

    f = File.new('1.txt')
    f.each do |line|
      if ((1..3).include?f.lineno) or (line =~ /eig/ or line =~ /nin/) then
        print f.lineno
        print line
      end
    end
    

      

  • 相关阅读:
    二分图大讲堂——彻底搞定最大匹配数(最小覆盖数)、最大独立数、最小路径覆盖、带权最优匹配
    POJ1469 COURSES
    HDU 1850 Being a Good Boy in Spring Festival(Nim博弈)
    取石子游戏(博弈)
    过山车(匈牙利算法)
    匈牙利算法与二分图
    HLG 1126 Final Destination II (转化为矩阵)(水题)
    快速幂与矩阵—>快速矩阵幂
    再论斐波那契数列(矩阵&快速幂)
    浮点数的陷阱--double i != 10 基本都是对的,不管怎么赋值
  • 原文地址:https://www.cnblogs.com/or2-/p/4447100.html
Copyright © 2011-2022 走看看