• ruby的迭代


    ruby中整数支持times,upto,downto,step等几种迭代

    irb(main):010:0> 3.times {print "X " }
    X X X => 3
    irb(main):011:0> 1.upto(5)  {|i| print i," "}
    1 2 3 4 5 => 1
    irb(main):012:0> 99.downto(95) {|i| print i," "}
    99 98 97 96 95 => 99
    irb(main):013:0> 50.step(80,5) {|i| print i," "}
    50 55 60 65 70 75 80 => 50
    irb(main):014:0>

    irb(main):019:0> 6.times do
    irb(main):020:1*   puts "#{num.class}: #{num}"
    irb(main):021:1>   num *=num
    irb(main):022:1> end
    Fixnum: 81
    Fixnum: 6561
    Fixnum: 43046721
    Bignum: 1853020188851841
    Bignum: 3433683820292512484657849089281
    Bignum: 11790184577738583171520872861412518665678211592275841109096961
    => 6
    irb(main):023:0>

    irb(main):006:0> three_times { puts "Hello"}
    Hello
    Hello
    Hello
    => nil
    irb(main):007:0> [1,3,5,7,9].find {|v| v*v>30}
    => 7
    irb(main):008:0> [1,3,5,7,9].each {|i| puts i}
    1
    3
    5
    7
    9
    => [1, 3, 5, 7, 9]
    irb(main):009:0> [1,3,5,7,9].injuect {|sum,element| sum+element}
    NoMethodError: undefined method `injuect' for [1, 3, 5, 7, 9]:Array
        from (irb):9
        from :0
    irb(main):010:0> [1,3,5,7,9].inject {|sum,element| sum+element}
    => 25
    irb(main):011:0> [1,3,5,7,9].inject {|sum,element| sum*element}
    => 945
    irb(main):012:0>



  • 相关阅读:
    2019年8月下旬
    2019年8月上旬
    2019年7月 vue专题
    2019年7月上
    mysql安装 demo [linux centos7] [5.7.26]
    记一个日志冲突——管中窥豹[java混乱的日志体系]
    Mybatis-Generator demo
    dubbo doc入门文档
    springBoot+mysql+mybatis demo [基本配置] [遇到的问题]
    nginx安装demo
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2415940.html
Copyright © 2020-2023  润新知