


根据题目中给出的案例,我可以简单得出,题目主要考察条件判断和循环,分为四种情况:
- 同时整除3和5得到"FizzBuzz"
- 只被3整除得到"Fizz"
- 只被5整除得到"Buzz"
- 其余数字输出其字符串格式
据此,我写出了如下代码:
n = 15
array = []
(1..n).each do |num|
if num%3 == 0 && num%5==0 then
array.push "FizzBuzz"
elsif num%3 == 0 then
array.push "Fizz"
elsif num%5 == 0 then
array.push "Buzz"
else
array.push num.to_s
end
end
puts array

执行代码后发现符合题目要求,不错没有测试的代码总归不完整,我打算看看如何对ruby代码进行单元测试,上网查询后发现test-unit是比较好的选择,先test.rb里写一个最简单的测试(1==1):
require 'test/unit'
class FizzBuzzTest < Test::Unit::TestCase
def test_judgeFB_is_right
assert_equal 1, 1
end
end
在当前工作目录下,执行sudo gem install test-unit
,安装成功后,在终端执行ruby test.rb

嘤嘤嘤,绿啦,接下来,给上述代码写个测试,过程很简单,就不码了,点击此处去github查看源码
网友评论