4Ruby分级题目参考答案

641 查看

闲话几句

最近学习Clojure语言,4Clojure这种分级题目的方式感觉不错,受此启发,网上没发现类似的Ruby题目,就自己收集一个,抛砖引玉。

欢迎大家推荐有趣的题目。

入门

1 . 显示“hello world”

puts 'hello world'

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

puts 3+2-5

3 . “hello world"转换为大写

'hello world'.upcase

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 

高级

  1. 值对象: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.(待定)


广告时间