美文网首页
Ruby完成FizzBuzz

Ruby完成FizzBuzz

作者: TW妖妖 | 来源:发表于2017-02-07 20:25 被阅读10次

题目要求

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”.
Example:
n = 15,
Return:
[ "1", "2", "Fizz", "4","Buzz", "Fizz", "7","8","Fizz","Buzz", "11","Fizz", "13", "14", "FizzBuzz"]

代码
# @param {Integer} n
# @return {String[]}
```def fizz_buzz(n)
    newArr = Array.new
    for i in 1..n
        if i%3==0 && i%5==0 
            newArr<< "FizzBuzz"
        elsif i%3==0
            newArr<< "Fizz"
        elsif i%5==0
            newArr<< "Buzz"
        else 
            newArr<< "#{i}"
        end
    end
    newArr
end

刚看到这道题目的时候以为以为很简单,很快写完,但一直不通过,后来仔细检查,发现要注意的地方还挺多。
一、刚开始只写了循环部分,并没有建立数组,导致打印出来只有结果,并不是一个数组,导致出错;
二、数组中添加元素的方法:
1、newArr.push("Fizz")
2、newArr<<"Fizz"
3、newAr.insert(2,"Fizz")

  • Ruby 字符串分为单引号字符串(')和双引号字符串("),区别在于双引号字符串能够支持更多的转义字符。在Ruby中,可以通过在变量或者常量前面加 # 字符,来访问任何变量或者常量的值。

三、


范围运算符

相关文章

  • Ruby完成FizzBuzz

    题目要求 Write a program that outputs the string representati...

  • 用Ruby完成FizzBuzz题目

    题目要求: 用ruby写一个程序:要求输出一个从1到n的字符串,其中遇到能被3整除的数字时,用“Fizz”代替该数...

  • FizzBuzz

    题目: 写一个程序打印1到100这些数字。但是遇到数字为3的倍数的时候,打印“Fizz”替代数字,5的倍数用“Bu...

  • FizzBuzz

    在学习ruby的过程中,我们有一道作业题https://leetcode.com/problems/fizz-bu...

  • FizzBuzz

    问题 你是一名体育老师,在某次课距离下课还有五分钟时,你决定搞一个游戏。此时有100名学生在上课。游戏的规则是: ...

  • cocoapods 安装和使用

    更新ruby 切换ruby源 执行完成应该显示 https://gems.ruby-china.com[https...

  • Rust 实例

    Writing an (Overly) Idiomatic Fizzbuzz with Rust[https://...

  • 《任务301》任务产出汇总

    任务地址### 《Ruby基础》 完成时间### 2016-12-14 任务要求的作业### 使用ruby完成这道...

  • TDD FizzBuzz

    FizzBuzz 说明 Write a program that prints the numbers from ...

  • 编码kata,再探FizzBuzz

    上一期kata,我们以责任链模式重构了FizzBuzz,相比原有代码,采用设计模式后,实际上将FizzBuzz中的...

网友评论

      本文标题:Ruby完成FizzBuzz

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