在Ruby中,代碼重構(gòu)可以通過以下方法使代碼更簡潔:
def calculate_total(price, tax_rate)
price * (1 + tax_rate)
end
total = calculate_total(100, 0.1)
def user_name=(new_name)
@user_name = new_name
end
class User
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def full_name
"#{@name} (#{@age})"
end
end
user = User.new("John", 30).full_name
module Loggable
def log(message)
puts message
end
end
class User
include Loggable
def initialize(name)
@name = name
end
end
user = User.new("John")
user.log("User created")
map
、reduce
、select
等,可以幫助你更簡潔地處理數(shù)組和集合。numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.map(&:squared)
? :
語法,可以根據(jù)條件選擇不同的值。status = if user.active?
"Active"
else
"Inactive"
end
and
、or
和not
關(guān)鍵字:這些關(guān)鍵字可以使條件表達(dá)式更簡潔。user_is_adult = user.age >= 18 and user.active?
通過遵循這些實踐,你可以使Ruby代碼更簡潔、易讀和可維護(hù)。