4Ruby分级题目参考答案

入门

1 . 显示“hello world”

`puts 'hello world'`

2 . 显示3+2-5的结果

`puts 3+2-5`

3 . “hello world"转换为大写

`'hello world'.upcase`

``````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"

a + b
end

class TestCalc < MiniTest::Test

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 ``````

高级

``````class EmailAddress
include Comparable

def initialize(string)
if string =~ /@/
else
raise ArgumentError, "email address must have an '@'"
end
end

def <=>(other)
end

def to_s
end

protected