最近學習Clojure語言,4Clojure這種分級題目的方式感受不錯,受此啓發,網上沒發現相似的Ruby題目,就本身收集一個,拋磚引玉。ruby
歡迎你們推薦有趣的題目。函數
1 . 顯示「hello world」單元測試
puts 'hello world'
學習
2 . 顯示3+2-5的結果測試
puts 3+2-5
ui
3 . 「hello world"轉換爲大寫scala
'hello world'.upcase
code
4 . 寫一個add加法函數,參數a、b對象
def add(a, b) a + b end
1 . 計算1到10的累加排序
(1..10).reduce(:+)
2 . 列表1..10中的每項乘2
(1..10).map {|n| n*2}
3 . 檢查字符串tweet是否包括單詞
words = ["scala", "akka", "play framework", "sbt", "typesafe"] tweet = "This is an example tweet talking about scala and sbt." p words.any? { |word| tweet.include?(word) }
1 . 實現快速排序
def qs a (pivot = a.pop) ? qs(a.select{|i| i <= pivot}) + [pivot] + qs(a.select{|i| i > pivot}) : [] end
2 . 寫出加法函數的單元測試
require "minitest/autorun" def add(a, b) a + b end class TestCalc < MiniTest::Test def test_add assert add(2, 5) == 7 end end
3 . 埃拉託斯特尼篩法,求120之內的素數
n=120 primes = Array.new for i in 0..n-2 primes[i] = i+2 end index = 0 while primes[index]**2 <= primes.last prime = primes[index] primes = primes.select { |x| x == prime || x % prime != 0 } index += 1 end p primes
值對象:EmailAddress
class EmailAddress include Comparable def initialize(string) if string =~ /@/ @raw_email_address = string.downcase.strip else raise ArgumentError, "email address must have an '@'" end end def <=>(other) raw_email_address <=> other end def to_s raw_email_address end protected attr_reader :raw_email_address end
2.(待定)