Hello , Ruby!

简介: QuestionWrite a program that outputs the string representation of numbers from 1 to n.

Question

Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Answer

程序中主要使用了

  • for i in start .. end循环结构,也可以用 times,while实现
  • if then else 选择结构
  • % 求余运算
  • and 与逻辑运算
  • 数组<<运算符 :数组元素追加,ruby的数组比较灵活,声明时可以不申明大小。
  • 方法定义:def function_name(args,...) ... end
# @param {Integer} n
# @return {String[]}
def fizz_buzz(n)
    result = Array.new()
    for i in 1 .. n
        if i % 3 == 0 and i % 5==0 then
          result << "FizzBuzz"
        else 
            if i % 3 == 0 then
              result << "Fizz"
            else 
                if i % 5 == 0 then
                result << "Buzz"
                else
                result << "#{i}"
                end
            end
         end
    end
    return result
end
目录
相关文章
|
4月前
|
Ruby
|
4月前
|
Ruby
Ruby 教程 之 Ruby 方法 2
Ruby return 语句
29 0
|
4月前
|
C语言 C++ Ruby
|
4月前
|
Ruby
Ruby 教程 之 Ruby 方法 3
可变数量的参数
37 1
|
1月前
|
程序员 Linux iOS开发
Ruby
Ruby
13 0
|
4月前
|
Ruby
|
10月前
|
编解码 前端开发 定位技术
|
Ruby
ruby安装
安装ruby curl -sSL https://rvm.io/mpapis.asc | gpg2 --import - curl -L get.rvm.
1258 0
|
Ruby Ubuntu