Ruby ——Fizz Buzz (2)

數組

  • 任何對象有序整數索引集合。
  • 數組的索引可以從為0 開始的正數,也可以為負數。一個負數的索相對于數組的末尾計數的,例如:索引為 -1 表示數組的最后一個元素。
  • 數組不需要指定大小,當向數組添加元素時,Ruby 數組會自動增長。
  • 數組的創建
# 只創建數組
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 語句用于從 Ruby 方法中返回一個或多個值。
return [expr[`,' expr...]]
  • 可變數量的參數
    Ruby允許聲明參數數量可變的參數。
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 方法

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容