第一天
找
-
Ruby API 文檔:http://ruby-doc.org/core-1.9.3/
-
Programming Ruby: The Pragmatic Programmer's Guide [TFH08]的免費在線版本:http://www.ruby-doc.org/docs/ProgrammingRuby/
-
替換字符串某一部分的方法:
替換一次:
"Hello World".sub('World','Ruby') => Hello Ruby
替換所有:
"This is not right".gsub('i',' ') => Th s s not r ght
-
有關Ruby正則表達式的資料:http://ruby-doc.org/core-1.9.3/Regexp.html
-
有關Ruby區間(range)的資料:http://ruby-doc.org/core-1.9.3/Range.html
做
-
打印字符串"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