Ruby小白,初来乍到

最近开始学习了Ruby,发现Ruby真是简约到可爱,清晰明了的语法格式,让人心花怒放。所以,迫不及待的想开始用Ruby写程序啦。
练习】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”.
分析】输入数字n,要求对1~n之间的数字进行处理后输出合适的结果:数字如果是3的倍数,输出“Fizz”;如果是5的倍数,输出“Buzz”;如果既是3的倍数,又是5的倍数,则输出“FizzBuzz”。

根据输出结果要求,需要新建一个数组res[]来保存处理后的结果
对1~n之间数字的遍历,使用for循环
对于数字的判断,使用if语句
判断数字i是否为m的倍数,使用i%m==0或者i==i/n*n
结果返回数组res[]

代码

def fizz_buzz(n)
    res=[]
    for i in 1..n
        if(i==i/3*3) then
             if(i==i/5*5) then
                 res[i-1]="FizzBuzz"
             else res[i-1]="Fizz"
             end
        elsif(i==i/5*5) then
              res[i-1]="Buzz"
        else res[i-1]=i.to_s
        end
     end
     return res
end

结果

Input:15
Output:["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz",
"Buzz","11","Fizz","13","14","FizzBuzz"]

结果详情可见:https://leetcode.com/problems/fizz-buzz/ (将Custom Testcase后面的选项打上√,就可以测试不同的输入啦)

心得】今天用Ruby实现了人生中第一个Ruby小程序,发现Ruby语法还是蛮贴心的,loving Ruby~

你可能感兴趣的:(Ruby小白,初来乍到)