最近学习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.(待定)