程序猿葵花宝典程序员Ruby

茴香豆有幾種寫法之 Loop

2015-02-13  本文已影响76人  jProvim

Loop

  1. loop

    number = 0
    loop do
      break if number > 15
      puts "The number is #{number}"
      number += 1
    end
    
  2. until

    until number > 30
      puts "The number is #{number}"
      number += 1
    end
    
  3. while

    while number < 40 do
      puts "The number is #{number}"
      number += 1
    end
    
  4. for

    for i in 1..8 do
       puts i
    end
    
  5. times

    16.times do |number|
      puts "The number is #{number}"
    end
    
  6. times oneliner

    5.times { |i| puts i }
    
  7. upto

    5.upto 10 do
      puts 'Hi'
    end
    
  8. downto

    15.downto(10) {|i| puts i }
    
  9. each

    list = [0, 1, 2, 3, 4]
    list.each do |number|
      puts "The number inside the loop is #{number}"
    end
    
  10. each without initializing list

    (0..15).each do |number|
      puts "The number inside the loop is #{number}"
    end
    
  11. for another form

    for number in 0..15
      puts "The number inside the loop is #{number}"
    end
    

牛人 現身, 繼續增加方法!

上一篇下一篇

猜你喜欢

热点阅读