Hello , Ruby!

作者: 极客人 | 来源:发表于2016-12-12 15:39 被阅读659次

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

相关文章

  • 测试文章

    #测试文章 ```ruby p "hello world" ```ruby

  • Test

    ```ruby def hello ```

  • Hello, Ruby!

    由于种种原因,简书等第三方平台博客不再保证能够同步更新,欢迎移步 GitHub:https://github.co...

  • Hello , Ruby!

    Question Write a program that outputs the string represen...

  • ruby 语法

    hello ruby 新建一个test.rb文件,在里面加一条 puts 'hello ruby',终端执行,ru...

  • ruby helloworld

    在Linux上:vim hello-world.rbputs 'Hello world' 让后执行ruby hel...

  • 谈谈Swift的extension

    3.times { puts 'hello world' }这是一条Ruby语句,它会打印“hello world...

  • 红宝石(Ruby)之路

    用Ruby实现的Hello World 将这句保存为test.rb,在terminal输入ruby test.rb...

  • Ruby on Rails的Hello World

    1. 根据「Mac上快速安装Ruby on Rails」一文中的4~6部建立一个名为demo的工程 2. 进入de...

  • ruby基础汇总

    在安装好ruby的环境之后,我们就可以来敲ruby代码了,首先我们先来个hello,world(每学一门语言,都是...

网友评论

  • 6d96978eeefb:进度很快,赞
    Pursue:哇,好快。不过其实Ruby是不需要return的,最后一行是什么就return什么,哈哈。
    极客人: @TW李鹏 😁
    极客人: @TW李鹏 😁

本文标题:Hello , Ruby!

本文链接:https://www.haomeiwen.com/subject/xsbmmttx.html