loops

  1. while and until
    x = 10
    while x >= 0 do
    puts x
    x = x- 1
    end
    # result: 10 9 8 7….0 

    x = 10
    puts x = x – 1 while x > 0
    # result: 10 9 8 7….0

    x = 10
    puts x = x – 1 while x >= 0
    # result: 10 9 8 7….0 -1x = 0
    until x > 10 do
    puts x
    x = x+ 1
    end
    #result: 0 1 2 3 … 10

    a = [1,2,3]
    puts a.pop until a.empty?
    #result: 3 2 1

  2. for/in loop
    array = [1,2,3,4,5]
    for element in array
    puts element
    end
    #result: 1 2 3 4 5hash = {:a=>1, :b=>2, :c=>3}
    for key,value in hash
    puts “#{key} => #{value}
    end
    #result: a=>1 b=>2 c=>3 

    hash = {:a=>1, :b=>2, :c=>3}
    hash.each do |key,value|
    puts “#{key} => #{value}”
    end
    #result: same as above

  3. Iterators and Enumerable Objects
    The times, each, map, and upto methods are all iterators, and they interact with the block of code that follows them.3.times { puts “thank you!” }
    #result: thank you thank you thank you 

    • 3.times { puts “thank you!” }  # Express gratitude three times
    • data.each {|x| puts x } # Print each element x of data
    • [1,2,3].map {|x| x*x } # Compute squares of array elements
    • factorial = 1 # Compute the factorial of n
      2.upto(n) {|x| factorial *= x }

    Numeric Iterators
    4.upto(6) {|x| print x}   # => prints “456”
    3.times {|x| print x }    # => prints “012”
    0.step(2, 0.1) {|x| puts x } # 0, 0.1, 0.2, … , 2

  4. Enumerable Objects
    [1,2,3].each {|x| print x }   # => prints “123”
    (1..3).each  {|x| print x }   # => prints “123”
    ##Same as 1.upto(3)
    1.upto(3) do |x|
    puts x
    end
    ## Same as
    1.upto(3) { |x| puts x}
    ###
    do … end  (==) { … } 

    #也可應用在開啟檔案內容
    filename = “ex.txt”
    File.open(filename) do |f|
    f.each { |line| print line }
    end

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • MySpace
  • Plurk
  • RSS
  • Google Buzz
  • Live
本篇發表於 Ruby。將永久鏈結加入書籤。

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *