七週七語言:Ruby Day 1

第一天

  • 打印字符串"Hello World.":

    irb>puts "Hello World."
    Hello World.
    => nil
            
  • 在字符串"Hello Ruby."中,找出"Ruby."所在下標。

    irb>"Hello Ruby.".scan(/[Ruby\.]/) { |x| puts "Hello Ruby.".index(x)}
    6
    7
    8
    9
    10
    => "Hello Ruby."
            

    其中,scan爲Ruby在字符串中掃描的函數,尋找到匹配"Ruby."中任意字符的字符,然後再用index方法求下標。

  • 打印你的名字十遍

    irb>10.times do puts "fanTasy" end
    fanTasy
    fanTasy
    fanTasy
    fanTasy
    fanTasy
    fanTasy
    fanTasy
    fanTasy
    fanTasy
    fanTasy
    => 10
            
  • 從打印字符串"This is sentence number 1.",其中的數字1會一直變化到10。

    irb>n = 0
        while (n<10)
        puts "This is sentence number"+(n+1).to_s+"."
        end
    This is sentence number 1.
    This is sentence number 2.
    This is sentence number 3.
    This is sentence number 4.
    This is sentence number 5.
    This is sentence number 6.
    This is sentence number 7.
    This is sentence number 8.
    This is sentence number 9.
    This is sentence number 10
            
  • 從文件運行Ruby程序

    用自己喜愛的文本編輯器寫好一個Ruby程序,保存之後在終端輸入:

    ruby fileName.rb
            
  • 猜數字程序:

    puts "Guess a number:"
    a = gets()
    b = rand(10)
    while true
       if a.to_i > b
          puts "Too large\n"
       elsif a.to_i < b
          puts "Too small\n"
       else
          puts "all right\n"
          exit
       end
       puts "Guess again:\n"
       a = gets()
    end
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章