4Ruby分级题目参考答案
闲话几句
最近学习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
高级
值对象: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.(待定)
Elixir练习
Elixir
推荐阅读
十分钟Elm
Elm is a functional reactive programming language that compiles to (client-side)JavaScript. Elm is statically typed, meaning that the compiler catches mosterrors immediately and provides a clear an...
chenge3k阅读 2.1k
手把手教你验证码检验的登录
在网站实际应用过程中,为了防止网站登录接口被机器人轻易地使用,产生一些没有意义的用户数据,所以,采用验证码进行一定程度上的拦截,当然,我们采用的还是一个数字与字母结合的图片验证码形式,后续会讲到更...
运维社阅读 315
Spring Security入门学习
认识Spring SecuritySpring Security 是为基于 Spring 的应用程序提供声明式安全保护的安全性框架。Spring Security 提供了完整的安全性解决方案,它能够在 Web 请求级别和方法调用级别处理身份认证和授权。因为...
运维社阅读 290
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。