Ruby ——Fizz Buzz (2)

2016-12-17  本文已影响11人  qin7zhen

数组

# 只创建数组
names = Array.new        
# 创建数组的同时设置数组的大小
names = Array.new(20) 
# 创建数组的同时给数组中的每个元素赋相同的值
names = Array.new(7, "0")
# 创建数组的同时设置各元素的值
nums = Array.[](1, 2, 3, 4,5)
nums = Array[1, 2, 3, 4,5]
# 使用一个范围作为参数来创建一个数字数组
nums = Array(1..5)

方法

def method_name [( [arg [= default]]...[, * arg [, &expr ]])] 
    process..
end
# 调用
method_name [arg [, ...,arg]]
def method_name (var1=value1, var2=value2) 
      process..
end
return [expr[`,' expr...]]
def sample (*test) 
    for i in 0...test.length
        code
    end
end
sample "Zara", "6", "F"

Fizz Buzz解析

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”.

分别对1到n中的3的倍数、5的倍数以及15的倍数进行特殊处理,其它数字直接保存。在编码过程中需要用到:数组,求余运算符,循环,条件判断,以及方法返回值。

代码

# @param {Integer} n
# @return {String[]}
def fizz_buzz(n)
    i=1
    results = Array.new(n)
    while i<=n do
        mod3 = i%3
        mod5 = i%5
        mod15 = i%15
        
        if mod15 == 0
            results[i-1] = "FizzBuzz"
        elsif mod3 == 0
            results[i-1] = "Fizz"
        elsif mod5 == 0
            results[i-1] = "Buzz"
        else
            results[i-1] = i.to_s
        end
        i = i + 1
    end
    return results
end

Reference

Ruby 数组(Array)
Ruby 方法

上一篇 下一篇

猜你喜欢

热点阅读