Ruby代碼風格規范通常遵循以下原則和方法:
使用2或4個空格的縮進。不建議使用制表符(Tab)進行縮進。
方法名使用小寫字母和下劃線的方式命名(snake_case),例如:user_name。
類名使用大寫字母開頭的駝峰命名法(CamelCase),例如:UserName。
常量名使用全大寫字母和下劃線的方式命名(CONSTANT_CASE),例如:MY_CONSTANT。
使用def關鍵字定義方法,并在方法名后加括號,例如:def my_method(param)。
在方法參數列表中,多個參數之間用逗號分隔,例如:def my_method(param1, param2, param3)。
使用and連接多個條件表達式,例如:if condition1 and condition2。
使用or連接多個條件表達式,例如:if condition1 or condition2。
使用not對條件表達式取反,例如:if not condition。
使用elsif表示“否則如果”,例如:if condition1 then ... elsif condition2 then ... end。
使用when表示“當…時”,例如:case value ... when value1 then ... when value2 then ... end。
使用begin、rescue、ensure和end關鍵字處理異常,例如:
begin
# 可能引發異常的代碼
rescue SomeException => e
# 處理異常的代碼
ensure
# 無論是否發生異常都會執行的代碼
end
使用class關鍵字定義類,并在類名后加括號,例如:class MyClass。
使用module關鍵字定義模塊,并在模塊名后加括號,例如:module MyModule。
使用extend關鍵字將模塊的方法包含到類中,例如:class MyClass; extend MyModule; end。
使用include關鍵字將模塊的方法包含到類中,例如:class MyClass; include MyModule; end。
使用attr_accessor和attr_reader關鍵字定義類的getter和setter方法,例如:
class MyClass
attr_accessor :name
attr_reader :age
def initialize(name, age)
@name = name
@age = age
end
end
each、map、select等方法遍歷數組,例如:array = [1, 2, 3, 4, 5]
# 使用each方法遍歷數組
array.each do |element|
puts element
end
# 使用map方法創建新數組
new_array = array.map { |element| element * 2 }
# 使用select方法篩選數組元素
filtered_array = array.select { |element| element % 2 == 0 }
for循環遍歷數組,例如:array = [1, 2, 3, 4, 5]
for element in array
puts element
end
while循環遍歷數組,例如:array = [1, 2, 3, 4, 5]
index = 0
while index < array.length
puts array[index]
index += 1
end
遵循這些原則和方法可以使Ruby代碼更加易讀、易維護和一致。在實際項目中,可以使用諸如Rubocop或Prettier等工具來自動檢查和格式化代碼。