• 读<<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
    

      

  • 相关阅读:
    回顾2018,展望2019
    NLog日志框架使用探究-1
    基于NetMQ的TLS框架NetMQ.Security的实现分析
    鸟哥的Linux私房菜笔记第五章,文件权限与目录配置(二)
    鸟哥的Linux私房菜笔记第五章,文件权限与目录配置(一)
    鸟哥的Linux私房菜笔记第四章
    ThinkPHP5.1 + tufanbarisyildirim 解析apk
    Java核心技术第八章——泛型程序设计(1)
    Java核心技术第五章——2.Object类
    Java核心技术第五章——1.类、超类、子类(2)
  • 原文地址:https://www.cnblogs.com/or2-/p/4447100.html
Copyright © 2020-2023  润新知